Featured Post

The great debacle of healthcare.gov

This is the first time in history when the president of the United States of America, or probably for any head of state around the world,...

Thursday, November 27, 2008

Be cautuios while using auto boxing and unboxing feature of Java 5

We recently migrated to Java 5 and started using the great auto boxing/unboxing feature of it. I've one method in a class that returns boolean primitive and I required to override it. I was so excited with this boxing feature that I started saving some lines of code by evaluating and returning the Boolean object directly. And when the code I started testing, had started throwing NullPointerException here and there. I got confused for sometime and took a little to understand while what happening there. Becuse the Java 1.4 debugging mindset was looking for a object that was accessed (using dot) but I didn't find any code that can cause that NPE. Then I realized that it is the Boolean object that was getting evaluated to primitives (actually Boolean.booleanValue() was invoked implicitely) and that is causing this NPE.

In prior to Java 5, as of my knowledge, this is first time Java evaluates any object internally and more over that is totally implicit. Once a programmer is used to of this feature he won't have any trouble but first time it is little confusing even though the theory is known to one

Resources:

http://fupeg.blogspot.com/2007/07/auto-unboxing-in-java.html

No comments: