Where Boxing Can Be Used

Picture from book I saw this example in a book where the author tries to talk about the use of boxing. I have a problem understanding the last lines, that is, "The code throws an exception when it tries to call doStuff (x) because x does not refer to the Integer object." I did not understand why x is not an object of the Integer Wrapper class. As if I defined it before as Static Integer x. Is this variable x not a reference to the Integer Wrapper class ?, Moreover, why does it throw a "NullPointerException?"

+4
source share
3 answers

I did not understand why x is not an object of the Integer Wrapper class.

x , : null.

, "NullPointerException?"

autounboxing - , , Integer int: Integer#intValue(). , :

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

..., .


, autounboxing, NPE, JLS & sect; 5.1.8, Unboxing. !

+7

doStuff(x), x null, . , x.intValue(), int . x - null, NullPointerException.

+4

An integer that is a reference type, a type variable Integercan contain nulleither a reference to an object Integer. They just want to say that if it xis null, you cannot convert it to int.

+1
source

All Articles