This is an exercise in Head First Java. The exercise is about autoboxing (wrapping and unwrapping).
Why does the compiler approve that assigning Integer i (default value is null) to int j (default value is 0)?
When I run it, it shows: "Cannot invoke "java.lang.Integer.intValue()" because "this.i" is null"
public class TestBox {
Integer i;
int j;
public static void main(String[] args) {
TestBox t = new TestBox();
t.go();
}
public void go() {
j = i;
System.out.println(j);
System.out.println(i);
}
}
Integer iis the declaration of an object reference. Object references are implicit initialized tonull. Thus you get aNullPointerExceptionat runtime.The compiler does not complain because the variable is neither declared
privatenorfinalso it might be initialized at runtime from outside of this class by code not yet written. Therefore the compiler cannot detect this as an error or warning.For that reason you should limit the visibility of variables. If you add the
privatekey word the compiler will issue a warning.