我刚刚发现 Java 以不同的方式处理变量初始化。
案例一:
class A {
boolean x;
public static void main(String[] args) {
A a = new A();
System.out.println(a.x);
}
}
当我运行上述程序时,输出显示为“false”。但现在我发布了另一段代码:
案例二:
class A {
public static void main(String[] args) {
boolean x;
System.out.println(x);
}
}
现在,上面的代码表明
java.lang.Error: Unresolved compilation problem:
The local variable x may not have been initialized
为什么同样的事情会有不同的处理方式? 提前致谢!
最佳答案
来自 Java Primitive Data Types 上的 Oracle 文档:
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
所以这是一个有趣的细微差别。如果原始类型变量是局部声明的,则必须为其指定一个值。
关于Java变量初始化的不同处理方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56087055/