public class memory {
int b;
public void main() {
int a;
System.out.println(a); /* complie time error */
System.out.println(b); /* here works how */
}
}
which assigns a default value to b
public class memory {
int b;
public void main() {
int a;
System.out.println(a); /* complie time error */
System.out.println(b); /* here works how */
}
}
which assigns a default value to b
You are using an uninitialized variable within a method and Java requires those to be initialized before you use them. They don’t get a default value. Class member variables and static variables do get a default value but not variables used within your method code.
The difference is class members are implicitly initialized, local variables are not.
Each type has a default, and obvious, value. For int
it’s 0
.
So these two class fields will have the same value are the instance in constructed:
public class memory {
int field1;
int field2 = 0;
You can’t access a (potentially) uninitialised variable. So to use a variable/field, no code path must exist that doesn’t result in a value being assigned to the variable.
For class fields, they are assigned the default value is one isn’t specified in the declaration. Local variables do not.