public class Foo {
public static void main(String[] args) {
float f;
System.out.println(f);
}
}
打印语句导致以下编译时错误,
The local variable f may not have been initialized
如果 Java 中的原语已经有 default value (float = 0.0f) ,为什么要我定义一个?
编辑:
所以,这行得通
public class Foo {
float f;
public static void main(String[] args) {
System.out.println(new Foo().f);
}
}
谢谢大家!
最佳答案
因为它是一个局部变量。这就是为什么没有分配给它的原因:
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 会引发此编译错误?
如果我们查看 IdentifierExpression.java
类文件,我们会发现这个 block :
...
if (field.isLocal()) {
LocalMember local = (LocalMember)field;
if (local.scopeNumber < ctx.frameNumber && !local.isFinal()) {
env.error(where, "invalid.uplevel", id);
}
if (!vset.testVar(local.number)) {
env.error(where, "var.not.initialized", id);
vset.addVar(local.number);
}
local.readcount++;
}
...
如前所述 (if (!vset.testVar(local.number)) {
),JDK 检查 (使用 testVar
) 变量是否已分配 ( Vset
's source code 其中我们可以找到 testVar
代码)。如果不是,它会从 properties file 引发错误 var.not.initialized
:
...
javac.err.var.not.initialized=\
Variable {0} may not have been initialized.
...
关于Java:为什么我需要初始化一个原始局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11165485/