Home » Core Java » Java AutoUnboxing Null pointer Exception

Java AutoUnboxing Null pointer Exception

AutoUnboxing Null pointer Exception

Autoboxing and Autounboxing concepts were introduced in jdk5. It is concept related to Wrapper Classes.

The conversion of primitive type into corresponding Wrapper class is called autoboxing.

e.g.  
Integer x = 10;
Character y = 'a';
Double d = 10.0;
Float f = 10.0f;

The conversion of Wrapper class objects into corresponding primitive types is called autounboxing.

e.g.
Integer x = 10;   //AutoBoxing
int x1 = x;   //AutoUnboxing
Character y = 'a'; //AutoBoxing
char y1 = y;  //AutoUnboxing
Double d = 10.0; //AutoBoxing
double d1 = d;   //AutoUnboxing
Float fx = 10.0f;   //AutoBoxing
float f1 = fx;   //AutoUnboxing

NullPointer in AutoUnboxing happens when we null object is unboxed. e.g.

Integer x = null;
int x1 = x;    /// would give Null Pointer Exception

Why does It give NullPointer Exception in AutoUnboxing on Null Object? – AutoUnboxing Null pointer Exception

Integer x = null;
int x1 = x;    /// would give Null Pointer Exception

In the above case, when object x is autounboxed, then the compiler actually converts it into this as below

Integer x = null;
int x1 = x.intValue();    /// would give Null Pointer Exception

Now as “x” is null, hence at Runtime, it would throw NullPointer Exception.


Leave a comment