Java:为什么我需要初始化一个原始局部变量? [英] Java: Why am I required to initialize a primitive local variable?
问题描述
public class Foo {
public static void main(String[] args) {
float f;
System.out.println(f);
}
}
print语句导致以下编译时错误,
The print statement causes the following compile-time error,
本地变量f可能尚未初始化
The local variable f may not have been initialized
如果Java中的原语已经有默认值(float = 0.0) f),为什么我需要定义一个?
If primitives in Java already have a default value (float = 0.0f), why am I required to define one?
所以,这是有效的
public class Foo {
float f;
public static void main(String[] args) {
System.out.println(new Foo().f);
}
}
谢谢大家!
推荐答案
因为它是一个局部变量。这就是它没有分配给它的原因:
Because it's a local variable. This is why nothing it's assigned to it :
局部变量略有不同;编译器永远不会为未初始化的局部变量分配
默认值。如果你不能
初始化声明它的局部变量,请确保
在尝试使用它之前为其赋值。访问
未初始化的局部变量将导致编译时错误。
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
类文件,我们会找到这个块:
Why Java raises this compilation error ?
If we look at the IdentifierExpression.java
class file, we will find this 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
的源代码我们可以找到 testVar
代码)。如果没有,它会从 var.not.initialized lib / javac.propertiesrel =noreferrer>属性文件:
As stated (if (!vset.testVar(local.number)) {
), the JDK checks (with testVar
) if the variable is assigned (Vset
's source code where we can find testVar
code). If not, it raises the error var.not.initialized
from a properties file :
...
javac.err.var.not.initialized=\
Variable {0} may not have been initialized.
...
这篇关于Java:为什么我需要初始化一个原始局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!