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?"
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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With