Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where Boxing can be used [closed]

Tags:

java

Picture from book i saw this example in book , where author is trying to tell the use of Boxing. I have problem in understanding the last lines i.e. "The code throws exception when it attempts to invoke doStuff(x) because x doesnt refer to Integer object." I didn't understand that why x is not an object of Integer Wrapper class. As if, i defined it before as Static Integer x. Is this x variable is not a reference to Integer Wrapper class ?? . Moreover , why it throws "NullPointerException?"

like image 840
user2985842 Avatar asked Dec 16 '22 03:12

user2985842


2 Answers

I didn't understand that why x is not an object of Integer Wrapper class.

Because x was never initialized, so it has the default value: null.

Moreover , why it throws "NullPointerException?"

Because autounboxing is just a method call inserted by the compiler to turn an Integer into an int: it calls Integer#intValue(). But there is no instance, so it's just like trying to do this:

Integer x = null;
int someInt = x.intValue();

...which should be pretty obvious.


The steps involved in autounboxing, including this NPE behavior is specified in the JLS § 5.1.8, Unboxing Conversion. Happy reading!

like image 116
Matt Ball Avatar answered Dec 17 '22 16:12

Matt Ball


When your code runs and you call doStuff(x), x is null because you haven't initialized it. The compiler will produce byte code that calls x.intValue() to pass an int to your method. Since x is null, you will get a NullPointerException.

like image 41
Sotirios Delimanolis Avatar answered Dec 17 '22 15:12

Sotirios Delimanolis