Item 61: Prefer primitive types to boxed primitives

Applying the == operator to boxed primitives is almost always wrong. The two boxed primitives can have same value and different identities, whereas the primitives have only values. Check the code below:

int a = new Integer(10);
int b = new Integer(10);
 	
// The values of the boxed primitives are the same, so true.
System.out.println(a == b); // true

// The identities the boxed primitives are different, so false
System.out.println(new Integer(10) == new Integer(10)); // false

When you mix primitives and boxed primitives in an operation, the boxed primitive is auto-unboxed. If a null object reference is auto-unboxed, you get a NullPointerException

static Integer i;
public static void main(String[] args) {
    if (i == 42) {
	System.out.println("Do not mix primitive and boxed");
   }
}

Auto-boxing and auto-unboxing cause significant performance degradation. Compare the performance of the code snippets below:

Integer sumBoxed = 0L;
for (int i = 0; i < Integer.MAX_VALUE; i++) { 
    sumBoxed += i;
}	

...
int sumBoxed = 0L;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
    sumBoxed += i;
}

Leave a Reply

Your email address will not be published. Required fields are marked *