I understand that Java objects that are only declared but not initialized are defaulted to the null
value, but then why doesn't the following compile and print out null?
String a;
System.out.println(a);
From section 16 of the JLS:
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
Your code will work for non-final fields (instance or static variables) as they are initialized as per section 4.12.5) but will cause a compile-time error for local variables due to this.
The same would be true if a
were a primitive variable. Here's a short but complete program showing all of this:
class Test {
static int x;
static String y;
public static void main(String[] args) {
System.out.println(x);
System.out.println(y);
int lx;
String ly;
System.out.println(lx); // Compile-time error
System.out.println(ly); // Compile-time error
}
}
Output of the first two lines once the non-compiling lines have been removed:
0
null
See more on this question at Stackoverflow