Java And The Sweet Science

Brad Mongar Java 3 Comments

Attention: The following article was published over 9 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

When you have been developing in Java for 15 years and a co-worker asks you to help them debug a null pointer exception, you don’t expect to be surprised. Usually it is quite obvious what is null and the only thing you need to do is find out why.

Sometimes it is a little more difficult because someone has created a chain of dereferenced objects. The other day I ran into something a little new to me and baffling for a period of time. One of the easiest things to debug in Java was a momentary mystery.

Consider the code below and tell me where the Null Pointer Exception is:

	return value;

That right, the NPE was being thrown on a simple return statement.

How could this be? There is no explicit dereferencing going on. No reference to be null. That statement is as simple as they come. Let me expand the code view a little bit for you to get a better idea of what is going on:

	public int getValue(){
		return value;
	}

Once again, we are looking at very simple code. Between the code above and the hint in the title of the article, you may have figured out what is going on or you may be more confused. Again nothing is being explicitly dereferenced. Not only that we aren’t even dealing with a reference, it is returning a primitive.

Have you figured it out from the clues yet? Okay, here is the rest of the code and the explanation:

package Example;
public
 class Example {
	Integer value;
	public int getValue(){
		return value;
	}
}

Notice that value is an Integer with a capital I and getValue return int.

In the old days before Java 5, you would have gotten a compile error on the above code. Java 5 however introduced Autoboxing. This feature has been around for almost half my Java career and had never stung or confused me. It has always been a convenient feature.

Autoboxing allows for seamless conversion between primitives and their first class object equivalents. So instead of calling value.intValue to get the primitive, you can just assign value. But under the covers it still calls the intValue method.

That is where the NPE happened. The line in question became:

	return value.intValue();

On that line, it is obvious where the NPE happens.

Oh, in case anyone missed it, the sport boxing is called the Sweet Science. I felt like I had been sucker-punched by Auto­boxing, thus the name of this article.

— Brad Mongar, [email protected]

0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments