The Integer you pass to doStuff is being boxed out (i.e converted into an int). To do so, Integer.intValue will be called on your variable, but because it is not initialized (it's null here), an NPE is thrown.
This would also happen if you'd call "int z = x;" without x being initialized.
I attempted to take this code a step further by overloading the doStuff method and initializing the static wrapper. I was expecting the end value of x to be 10, but it is actually 5. I don't understand what is happening.
Here is the output:
$ java Box6
Value of i in doStuff(Integer) is : 10
Value after doStuff is : 5
Well wrappers are immutable, so if you reassign a value to them, then a new object is created.
And this is just one part of the story. Since you are using the wrapper in a method call, so it will be passed as a reference pointer (this is what I call it). If it was a primitive, then there was no chance of change in the value of original variable as primitives are passed as value. But even if we pass a reference to the method, the original value of x will not change as in doStuff, a new object will be created o point to the value 10 and x will still point to the Integer object with the value 5. I hope it is clear...
I appreciate Ankit's most interesting observation about about Integer instances being immutable. I'd like to request some moreinfo about this, because I'm concerned about how to recognize when an object is immutable.
In the following code,
static Integer fn1(Integer i)
i = i + 1;
static Animal fn2(Animal a)
a.name = "New name";
Animal b = a;
Consistent with what Ankit has said, fn1() does not change the value of the ARGUMENT i, since Integer is immutable. fn2() does change the value of the ARGUMENT a; the "name" field is "New name".
I would be most curious if anyone knows which classes are immutable, and which are not. Of course, String is immutable. I believe that Date is immutable. Can anyone provide a list of immutable classes? Is there a way to define your own class, and make it immutable?