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?
help appreciated, Max
Jeroen T Wenting
Ranch Hand
Joined: Apr 21, 2006
Posts: 1847
posted
0
you're trying to unbox null. That might be undefined behaviour though I'd guess it could have been implemented as resolving to 0 in this specific case.
Java has no pointers, at least none you, the programmer, can access.
42
abhishek jain
Greenhorn
Joined: Aug 18, 2004
Posts: 4
posted
0
Hi Max,
There is an obvious compile time error (incompitable types) at line ... i = j;
I am surprised how come you have compiled your code ??
Plese check whether you have compiled the same source file ?
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.