Core Java Tutorials : Primitives vs Boxed Primitives

By Yashwant
Feb 22nd, 2014
2 Comments
2908 Views

One of the coolest features of Java 1.5 was addition of AutoBoxing and AutoUnboxing. Primitives and Boxed Primitives can be interchanged without using new(). It made job of programmers a bit easy in certain cases but sometimes we overuse the features provided by language without even thinking about the downsides of the same. Same is the case with Boxing and Unboxing. Before understanding the side effects of boxing and unboxing, first let’s try to understand difference between primitives and boxed primitives

Core Java Tutorial : Primitives vs Boxed Primitives

Core Java Tutorial : Primitives vs Boxed Primitives

  • Primitives always have fully functional values while Boxed Primitives can be null (This leads to Null Pointer Exceptions when programmer doesn’t take care of initialization of Boxed Primitives)
  • Primitives only have values while Boxed Primitives have identity separate from value also. For example two different Long objects can have value of 42 still they won’t be equal if == is used for comparision as == compares for instance and not the logical value. (This leads to HardToDetect logical errors in code because it will never give compilation error and most of the time the particular error scenario might not be tested)
  • Primitives are generally more time and space efficient than Boxed Primitives.

Example 1 : Now we have seen the differences between the two, lets see what harm can unnecessary boxing and unboxing cause. Have a look at following code

Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println("Sum : " + sum);

This code looks pretty straight forward and most of us have written code like this. Now have a look at the very first line : it uses Long and not long. Inside loop we use sum+=i; which causes first auto unboxing to compute the sum and then auto boxing to assign the value back to sum variable of type Long. This unncessary boxing and unboxing causes severe performance degradation. I have attached a test java file with the example and I have got huge difference in execution time with Long and long – 24158 ms and 5566 ms. I tried one more thing and kept i also as Long and this time the processing time went upto 47586 ms. So you can see the performance impact of such a small mistake.

Core Java Tutorial : Primitives vs Boxed Primitives

Core Java Tutorial : Primitives vs Boxed Primitives

Example 2 : First example was related with performance, now let’s see another example which causes Null Pointer Exception

static Integer i;
public static void shocking() {
if(i == 1)
System.out.println("Shocking !!");
else
System.out.println("Expected !!");
}

Another straight forward code which should print “Expected” but it throws NPE because i is declared as Interger and not int, so it is not instantiated.

Example 3 : Here is one example of instance comparision instead of value comparision

public static void compare() {
Comparator naturalOrder = new Comparator() {
public int compare(Integer first, Integer second) {
return first < second ? -1 : (first == second ? 0 : 1);
}
};
Integer i = new Integer(21);
Integer j = new Integer(21);
System.out.println(naturalOrder.compare(i, j));
}

This method prints 1 instead of 0 because first == second compares objects and not object values. This method can be improved to work propery by using two local int variable and comparing them.

public static void improvedCompare() {
Comparator naturalOrder = new Comparator() {
public int compare(Integer first, Integer second) {
int f = first; int s = second;
return f < s ? -1 : (f == s ? 0 : 1);
}
};
Integer i = new Integer(21);
Integer j = new Integer(21);
System.out.println(naturalOrder.compare(i, j));
}

You can download the source code for examples mentioned in this post here – SlowAutoboxing.java

Please share your suggestions in comments. Also visit other Java Tutorials and Java Interview Questions.

About the Author

- An avid reader and a big time comics fan. A software engineer by profession who loves writing code and make things work.

2 Responses to “Core Java Tutorials : Primitives vs Boxed Primitives”

  1. Bala says:

    Nice article!! Thanks for sharing

Leave a Reply

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

facebook comments: