SyntaxHighlighter JS

2013-01-21

Java Gotchas: Boxed Primitive

Primitives are int, double, boolean, etc. Boxed primitives are the Object version of primitives, i.e. Integer, Double, BooleanAs a general rule, prefer using primitives over boxed primitives.

Gotchas
1.) Do not use the == operator to compare boxed primitives.
     

            Integer a = new Integer(7);
     Integer z = new Integer(7);

     System.out.println(a == z);

Prints out false because == is doing an identity comparison on the Integer   reference memory location.  Since object a and object z are two different objects in different areas of memory, the (a == z) test is false.

To do an equality test on boxed primitives, use the equals method.

           a.equals(z);

Or unbox the boxed primitive and then do the == test

     int x = a;
     int y = z;

     System.out.println(x == y);

2.) Do not unbox in a loop

     Long sum = 0L;
     for (long i = 0; i < Integer.MAX_VALUE; ++i) {
         sum += i;
     }

At code sum += i , the boxed primitive sum will be auto-unboxed to perform addition then a Long object created to assign to sum.  This caused time and space performance issues.

Fix the above code by changing sum to a primitive long.

3.) Boxed primitives can throw NullPointerException
   
     static Integer i;
           
     public static void main(String... args) {
         System.out.println(i == 42);
     }

The code i == 42 will throw a NullPointerException because when i gets auto-unboxed to do a comparison with primitive int 42, the variable i is null;

No comments:

Post a Comment