Autoboxing and Unboxing in Java with example

Autoboxing and Unboxing in Java with example

Before trying to understand about autoboxing and unboxing, it is important to know about wrapper classes. In Java, Collections accepts only objects to be added to them. So in order to add primitive types to collections, wrapper classes were introduced. Wrapper classes are nothing but an object equivalent of their corresponding primitive types i.e. it wraps the primitive value into an object. For example Integer is the wrapper class for the primitive type int, Double is the wrapper class for the primitive type double and so on. Before introducing autoboxing and unboxing, the conversion has to be done manually. Autoboxing and Unboxing was introduced in Java 1.5.

What is Autoboxing and Unboxing?

Autoboxing is the automatic conversion of primitive types into their corresponding object wrapper classes e.g. int into Integer. Unboxing is the reverse process wherein wrapper class object will be converted to its primitive value. This conversion is done by the Java compiler. Below is the pictorial representation of it.

autoboxing and unboxing in java with example

Autoboxing Example:

 

What actually compiler does is that it calls the valueOf() method available in the respective wrapper class. So in the above code it calls Integer.valueOf() method which returns an Integer object. (The primitive value will be set in the final variable value in the returned object). This is the method we would have used manually if there is no autoboxing.

Integer Cache

Integer wrapper objects have a special case when it comes to autoboxing. To understand what is integer cache let us consider the below example.

 

When you run the above program, you will be surprised to see the output which is,

true

false

We all know that == operator compares object references. So in the above example both the output should be false.

Here comes the concept of Integer cache. The Integer class actually contains a cache of Integer objects for int values from -128 to 127. So when doing autoboxing, wherever the int values from -128 to 127 are used, same Integer objects for that value will be returned i.e. the Integer.valueOf() method returns the same Integer object reference(cached object for the int value) for int values -128 to 127. So in the above program same Integer object is returned for references i1 and i2. So i1 and i2 refers to same integer object. Since the value 130 is beyond the range, autoboxing returns different Integer objects. Hence i3 and i4 refers to different integer object. Hence the result.

Note:

  • This is applicable for Integer values in range between –128 to +127.
  • This Integer caching works only on autoboxing. Integer objects will not be cached when they are built using the constructor i.e new Integer(value).

 

The Javadoc states that,
The cache is initialized on first usage.  The size of the cache may be controlled by the –XX:AutoBoxCacheMax=<size> option. During VM initialization, java.lang.Integer.IntegerCache.high property may be set and saved in the private system properties in the sun.misc.VM class.

This cache was introduced to save memory and improve the performance.

Apart from Integer objects, cache is defined for Byte, Short, Long and Character as well.

Unboxing Example

 

During unboxing the Java compiler calls the xxxValue() method to get the primitive value of the object. So in the above example the compiler actually calls intValue() method to get the int value.

Points to remember

  • Autoboxing can happen anywhere where an object is expected and primitive type is available, for example, in method invocation where an object argument is expected but primitive value is passed.
  • Unboxing can happen anywhere where primitive type is expected and an object is available, for example, a method returns an integer object and is assigned to primitive int variable.
  • When you compare two objects using “==” operator, it compares object’s address and not value and also no auto boxing occurs here. Also you should be aware of cache while using the equality operator.
  • Another mistake to avoid while using autoboxing and unboxing in Java is mixing primitive and Object in equality or relational operator. When comparing a primitive type with another object there is a possibility of NullPointerException to be thrown when unboxing is done. For example,

           static Integer i;

           public static void main(String[] args) {

                 if (i >= 0) { // NullPointerException on unboxing

                     System.out.println(“i is positive”);

                 }

          }

In Summary, Autoboxing and unboxing lets developers write cleaner code, making it easier to read. But we should be careful while using them especially when using with equality operator. Better to use equals() method for object comparison.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

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