RSS Feed for This PostCurrent Article

Java: Be Careful of Autoboxing

For program written with JDK 1.5,  I have seen code written similar to the followings

public static void main(String[] args) {
    Long calculatedValue = 100;
    for (int i = 0; i < 100; i++) {
         calculatedValue += i;
    }
    System.out.println(calculatedValue);
}

The code compiled and run perfectly for JDK 1.5. The only thing is that behind the scene there are unnecessary objects creations.

calculatedValue is declared as Long and every time during calculation autoboxing is done to convert the value from Long to long, and objects are created unnecessarily.

You should use primitive types if possible, instead of boxed primitives like Long, Integer, Double.


Trackback URL


Sorry, comments for this entry are closed at this time.