public class Foo {
public static void main(String[] args) {
float f;
System.out.println(f);
}
}
The print statement causes
Class fields (non-final
ones anyway) are initialized to default values. Local variables are not.
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler.
So a (non-final
) field like f
in
class C {
float f;
}
will be initialized to 0f
but the local variable f
in
void myMethod() {
float f;
}
will not be.
Local variables are treated differently from fields by the language. Local variables have a well-scoped lifetime, so any use before initialization is probably an error. Fields do not so the default initialization is often convenient.
Hi guys solution is simple. the values that are stored on the heap memory are initialized by the compiler based datatype but local variables are stored on stack memory so we have to inialize it explictly.
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.
Actually local variables are stored in stack.Hence there is a chance of taking any old value present for the local variable.It is a big challenge for security reason..Hence java says you have to initialise a local varible before use.
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