public class Foo {
public static void main(String[] args) {
float f;
System.out.println(f);
}
}
The print statement causes the following compile-time error,
The local variable f may not have been initialized
If primitives in Java already have a default value (float = 0.0f), why am I required to define one?
So, this works
public class Foo {
float f;
public static void main(String[] args) {
System.out.println(new Foo().f);
}
}
Thanks, everyone!
Because it's a local variable. This is why nothing is 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.
Edit: Why does Java raise 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++;
}
...
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.
...