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

234 views Asked by At

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

There are 2 answers

0
Timothy Truckle On BEST ANSWER

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.

0
pcsutar On

There are two types of exceptions in java:

  1. Runtime exceptions - which occurs at runtime
  2. Compile time exceptions - which occurs at compile time

The exception thrown by your program is a Runtime exception and that is the reason your program got compiled successfully but due to runtime exception it has been failed.