Pages

Monday, May 14, 2012

Use primitives over boxed primitives whenever you have the choice - Java

Just with the reading of this post's title, some of you may be confused because, some of the java developers have used to use boxed primitives (Wrapper class objects of primitives) without a specific reason. But, We should be care of using primitives rather than the boxed primitives when We have a choice. I will explain Why, We should choose primitives.

There are differences between primitives and boxed primitives though You did not pay attention too much on that.

Primitives are simpler and faster, and they have only their values. Primitives are generally more time- and space-efficient than boxed primitives. But the boxed primitives have different identities though they have same value. Consider the following code which most of the java developers are well known and understandable.

 Integer first = new Integer(41);
 Integer second = new Integer(41);
  
 if (first == second) {
      System.out.println("Equal");  
 }

As You well known, the above code will not print the "Equal" since it performs an identity comparison on the two object references. Applying == operator on boxed primitives always gives wrong output. To fix the above problem, either You can use Integer's equal() method or getting integer values from Integer's intValue() method. Now, You consider the following code.

Integer first = new Integer(41);
Integer second = new Integer(41);
       
if (first > second) {
     System.out.println("First is greater than Second");  
} else {
     System.out.println("First is not greater than Second");
}

Can you spot the output of above code? The above code will print the else condition. In this case, it did not perform the identity comparison like == comparison. It compared the actual values and gave the correct output. So When evaluating this kind of comparison, Integer instances are auto-unboxed;that is, it extracts their primitive values. I know, You have used this kind of comparison plenty of times. Think, You really knew about this. So We must choose primitives or boxed primitives when We have a choice. 

Next, We will move to another difference. You know that, When We declare a variable with primitive type, it always has functional values. But boxed primitives can have 'null' values which sometime can raise exception. Consider the following example.


package com.semika.mail;

public class BoxPrimitiveTest {
 
static Integer x;
static int y;

public static void main(String[] args) {

   if (x == 0) {
        System.out.println("X is Zero");  
   }
  
   if (y == 0) {
        System.out.println("Y is Zero");  
   }
}
}

What will be the output of the above program. The above code will not run and it will throw an exception. As You can see, variable 'x' is declared with boxed primitive type. It has 'null' value when evaluating the x==0 expression. When a null object reference is auto-unboxed,You get a NullPointerException

Next, I will explain the harm of mixing both box primitives and primitives in a single operation. When You mix primitives and boxed primitives in a single operation, the boxed primitive is auto-unboxed which results severe performance problems. Consider the following class.

class LineItem {
 
double price;

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}
}

Suppose, You want to iterate list of 'LineItem' and calculate the total value. Note that 'price' variable is declared with a primitive type. Look into the following code of calculating total cost.

Double totoalCost = 0.0; 
  
for (LineItem lItem : lineItemList) {
    totoalCost += lItem.getPrice();
}

The above code makes a server performance problem. Since, You have declared 'totoalCost' variable to be of the boxed primitive type Double instead of primitive type double. The program compiles and run without an error or warning.But the variable is repeatedly boxed and unboxed, causing the observed performance degradation.

Finally, the developer should never ignore the distinction between primitives and boxed primitives. You have to choose what to use.

0 comments:

Post a Comment

Share

Widgets