This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a doubt in an example given in exam-watch section on wrapper classes.
It has a Wrapper class object passed to to method that accepts PDT equivalent and what happens if Wrapper object is null.
It would throw NullPointerException.
But i dont understand how it works.
why the exception is thrown if its void go(int x) here and not in case of - void go(Integer x)
Here you get compiler error when you use PDT because in that case the value of an Integer reference variable(null) is being assigned to an int variable. Had that value being any number it would have not given any compiler error however in this case as the Integer reference variable has not been assigned any value it will get a default value of null and when this value is assigned to int variable it would result in compiler error due to incompatible types.
The compiler would expect an int type however it will find <nulltype> and thus compiler error.
Unboxing is a funda in java in which compiler identifies that when the programmer is trying to assign a wrapper to premitive type, it calls the corresponding function to return the premitive type. (As Integer.intValue() in case of integer)
The java compiler converts your code to the code as mentioned below.
In this function, at runtime the interpreter tries to call x.intValue(). As we know that the value of x is null. so It returns null pointer exception.
I hope this would clear your confusion.