Java: Why am I required to initialize a primitive local variable?
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.
...
Source
In fact, the compiler does not assign a default value to your float f
, because in this case it is a local variable -- and not a field:
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.