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?
Edit:
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 :
Edit: Why does Java raise this compilation error ?
If we look at the
IdentifierExpression.javaclass file, we will find this block :As stated (
if (!vset.testVar(local.number)) {), the JDK checks (withtestVar) if the variable is assigned (Vset‘s source code where we can findtestVarcode). If not, it raises the errorvar.not.initializedfrom a properties file :Source