0

Code:-

Integer value =null;
int a = value;

Output:-

Exception in thread "main" java.lang.NullPointerException

I understand that unboxing failed because there is not int value for null reference.But can anyone tell me the method invoked which lead to nullPointerException

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35

2 Answers2

4

While assigning the reference type Integer to corresponding primitive type int Unboxing conversion happens. It is defined in jls-5.1.8 Unboxing Conversion:

If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()

So, when you are trying to unboxing it, the value.intValue() gets called resulting in NPE, as value is null

Sage
  • 15,290
  • 3
  • 33
  • 38
2

You first have to understand that the code you have is actually compiled to something a little different.

[s_delima@ml-l-sotiriosd bin]$ /usr/java/latest/bin/javap -c Test.class 
Compiled from "Test.java"
public class Test {
  ...   

  public static void main(java.lang.String[]) throws java.io.IOException;
    Code:
       0: aconst_null   
       1: astore_1      
       2: aload_1       
       3: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
       6: istore_2      
       7: return        
}

You will notice that there is an invocation of java/lang/Integer.intValue(). Since your Integer variable is referencing null, you will get a NullPointerException when the invocation tries to dereference it.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724