Autoboxing and its pitfalls

Autoboxing

What is Autoboxing?

Autoboxing is a feature of Java language introduced in Java 1.5.  When Java compiler makes automatic conversion between the primitive types and their corresponding object wrapper class, it is called autoboxing.  The process of creating a Wrapper class like Float from a primitive type like float is called boxing.  And the process of creating primitive type like int from Wrapper class like Integer is called unboxing.

 Why do we need Autoboxing?

  A primitive type cannot be put into a collection as collections can only hold object references. So as to put a primitive type to collections a programmer would have to always box a primitive type and put into collections. And then on retrieval of the value he/she would have to unbox it. This would be a pain and was so until java 1.4.  The auboxing and unboxing automates this and hence makes the code easier to read and less painful for developers to write.

Pitfalls of Autoboxing

Performance

Autoboxing does create objects which is not clearly visible in the code. So when autoboxing occurs performance suffers. If you see the java docs;

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

Unexpected behavior

Confused equals

Autoboxing has bought with itself a lot of things that just are not obvious to a programmer.  What would be the output of below code?

Long longWrapperVariable=2L ;
System.out.println(longWrapperVariable.equals(2));
System.out.println(longWrapperVariable.equals(2L));

Here is what the above code prints

false
true

If you are wondering what happened above,  2 was boxed to Integer and hence equals could not compare it with Long. And 2L was boxed to Long and hence returned true.

Caching of primitive by Wrapper classes

And on top of that if you add the below Java Language Specification, you would just be adding more confusion

” If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.”

Here is simple example that demonstrates the caching of int

System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));

What would be the result of above code?

true
false

This works on a JVM that is only caching int between -128 to 127.

Ambiguous method calls

What would be the result of below code?

public static void main(String[] args) throws Exception {
int test = 20;
myOverloadedFunction(test);
}

static void myOverloadedFunction(long parameter) {
System.out.println("I am primitive long");
}

static void myOverloadedFunction(Integer parameter) {
System.out.println("i am wrapper class Integer");
}

And the output is:


I am primitive long

The answer is that the compiler will choose widening over boxing, so the output will be “I am primitive long”.

OutOfMemoryError

A boxing conversion may result in an OutOfMemoryError if a new instance of one of the wrapper classes (Boolean, Byte, Character, Short, Integer, Long, Float, or Double) needs to be allocated and insufficient storage is available.

Ternary Operator madness

Would you expect this code to compile

  long madness= false ? 1 : null;

Guess what! This code compiles fine. I am assigning a null to a primitive type. But it will always throw a NullPointerException. This is because compile tries to unbox null.

NullPointerException

  While running the below code, NullPointerException(NPE) can be thrown and it is not quite obvious from the code if you are not aware of autoboxing. Eclipse will show the warning for this code, “Null pointer access: This expression of type Boolean is null but requires auto-unboxing”. Because I made it obvious to eclipse that testNPE variable is null.
Boolean testNPE = null;   
if(testNPE){
 System.out.println("will never reach here");
}
Let me make it less obvious to the eclipse in the below code.  And the warning will be gone but the possibility of NullPointerException still exists, as we are not handling the case of Boolean variable being null.
private void testAutoUnboxingNPE(Boolean testNPE) {
 if(testNPE){
  System.out.println("I am true");
 } else if(testNPE){
  System.out.println("I am false");
 }
}
How to avoid this NullPointerException in Boolean unboxing?

Here is the ugly code to avoid the exception. Here we handle it in a way that accepts that Boolean has 3 possible values, null, true or false.

private void testAutoUnboxingNPE(Boolean testNPE) {
 if(Boolean.TRUE.equals(testNPE)){
  System.out.println("I am true");
 } else if(Boolean.FALSE.equals(testNPE)){
  System.out.println("I am false");
 } else{
  System.out.println("I am null");
 }
}

So from the above code it is obvious that you have define the behavior of the above method in case Boolean object is null. I usually document the behavior of the method for all three case in the javadocs.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.