Hello, I'm going through Head First Java and I've come to one of the "sharpen your pencil" questions that is giving me a little trouble. It's on page 291 regarding autoboxing:
So, yes it does compile but gives a null pointer exception at runtime. Am I understanding the code correctly?
*A new reference variable "t" is created that refers to: *A new instance of the TestBox class is created *This new TestBox object has a Integer wrapper object that holds an int "i" variable and TestBox has a int instance variable "j".
Is the null pointer exception comming from "i" not having been set to a particular int(so it's essentially wraping null) and then attempting to set "j" to null? Would the correct term be autoboxing null?
I wish the sharpen your pencil answers were available for the later chapters. So Java has pointers after all?
I agree with you. I wish that the Sharpen Pencil exercises had answers for later chapters as well!!
So, to your question: In Chapter 4 (Page 84 in the second edition) of the HeadFirst book, it says that references that you don't initialize in your code by yourself are given a default initialization of null.
So, in your example from the book, Integer i is given a value of Null when you create the TestBox object. When you try to do "j=i;", autoboxing comes into play, which will automatically try to get the int value from Integer i and assign it to int j.
It automatically does something similar to:
j = i.intValue();
But since Integer i is null, you get a null pointer exception.
Java does not have pointers, but only references; if a method is called on a null reference, then you'll get that exception.