javajvmautoboxingjavacompiler

Why the code that the compiler approves but cannot be run by JVM?


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);
   }
}

Solution

  • Integer i is the declaration of an object reference. Object references are implicit initialized to null. Thus you get a NullPointerException at runtime.

    The compiler does not complain because the variable is neither declared private nor final so 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 private key word the compiler will issue a warning.