-1

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);
   }
}
Michael
  • 41,989
  • 11
  • 82
  • 128
Allen
  • 11
  • 5
  • Your program is being run by the JVM. It just encounters an error during runtime. Not every potential error can be found during compile time. Errors that just happen during run-time are something that you will have to live with. – OH GOD SPIDERS Jun 01 '21 at 16:58
  • The compiler does not know any values at compile time. It is generally allowed to assign a `Integer` to an `int`, so the compiler cannot fail. During runtime the program runs into an issue, since it cannot assign a `null` value of the `Integer` to an `int`. For more details about errors that can be found during compile time and/or during runtime have a look at @OHGODSPIDERS reference. – Philipp Jun 01 '21 at 17:00
  • The compiler does not care about the default values. It doesn't keep track of what the values are or are likely to be. Yes, auto-unboxing is an opportunity NPEs can occur. So is calling `i.toString()`. For a compiler to able to realistically prevent these kind of issues, you need nullity built into the type system. e.g. `Integer` and `Integer?` (nullable integer), [like Kotlin has](https://kotlinlang.org/docs/null-safety.html#nullable-types-and-non-null-types) – Michael Jun 01 '21 at 17:02
  • Thank you all!!! – Allen Jun 01 '21 at 20:21

2 Answers2

0

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.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
0

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.

pcsutar
  • 1,715
  • 2
  • 9
  • 14