Saturday, December 20, 2008

Auto unboxing pitfall

Lets try a simple code snippet to see how unboxing of null works.

public class TestAutoBoxingUnboxing {
     public static void main(String[] args) {
         Integer a = null, b = null;
         int iAmA = a;
         int iAmB = b;

         //Will this print???
         System.out.println("Lets see the primitive ints " + iAmA + " and " + iAmB);

Running the code produces:
Exception in thread "main" java.lang.NullPointerException at TestAutoBoxingUnboxing.main(


Cannot unbox null, it will throw a NullPointerException. So we have to be more careful with primitives than before to avoid such problems.

No comments:

Post a Comment