What is autoboxing and unboxing in Java?

Autoboxing & unboxing

Autoboxing & unboxing

Overview: In this article we will discuss about the autoboxing / unboxing feature of java. Autoboxing and unboxing is basically a feature to convert primitive data types to Objects and reverse. The entire process is done automatically by java run time environment. But care should be taken while implementing this feature otherwise it will have effect on application performance.

Introduction
Prior to JDK 1.5, it was not easy to convert primitive data types e.g int, char, float, double into their object equivalent – Integer, Character, Float, Double. JDK 5 came with the feature of automatic conversion of primitive data types into their object equivalent. This feature is known as autoboxing. The reverse of this is known as unboxing. i.e. the process of converting objects into corresponding primitive data types is called unboxing. Sample code for both autoboxing and unboxing is shown as under –

Autoboxing

[code]

Integer integer = 9;

[/code]

unboxing

[code]

int in = 0;

in = new Integer(9);

[/code]

When Autoboxing and unboxing is used?

Autoboxing is applied by the java compiler in the following conditions –

  • When a primitive value is passed as a parameter to a method which expects an object of the corresponding wrapper class.
  • When a primitive value is assigned to a variable of the corresponding wrapper class.

Consider the following example –

Listing1: Sample code showing Autoboxing 

[code]

public int sumEvenNumbers(List<Integer> intList ) {    int sum = 0;    for (Integer i: intList )        if ( i % 2 == 0 )            sum += i;        return sum;}

[/code]

Prior to jdk 1.5, the above code snippet would have resulted in compilation error since the remainder operator – ‘%’ and the unary plus – ‘+=’ could not be applied on Integers. But since jdk 1.5 this piece of code compiles and runs without any error as it converts an Integer to int at runtime.

Unboxing is applied by the java compiler in the following conditions –

  • When an object is passed as a parameter to a method which expects the corresponding primitive value.
  • When an object is assigned to a variable of the corresponding primitive type
  • Consider the following example –

Listing2: Sample code showing Unboxing

[code]

import java.util.ArrayList;import java.util.List; public class UnboxingCheck {                     public static void main(String[] args) {        Integer in = new Integer(-8);         // 1. Unboxing through method invocation        int absVal = absoluteValue( in );        System.out.println( “absolute value of ” + in + ” = ” + absVal );         List<Double> doubleList = new ArrayList<Double>();                    // It is autoboxed through method invocation.        doubleList.add(3.1416);             // 2. Unboxing through assignment        double phi = doubleList.get(0);        System.out.println( “phi = ” + phi );    }                     public static int absoluteValue( int i ) {                                         return (i < 0) ? -i : i;                    }}

[/code]

Autoboxing and unboxing allows the developer to write code which is easy to read and understand. The following table shows the primitive datatypes and their corresponding wrapper objects –

Primitive Type Wrapper Class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short

Table – 1:  Primitive data type and their equivalent wrapper classes With Comparison operators

Autoboxing and unboxing can be done with comparison operators. The following code snippet illustrates how it can be done –

Listing3: Sample code showing Autoboxing and unboxing using comparison operators

[code]

public class BoxedComparator {

public static void main(String[] args) {

Integer in = new Integer(25);

if (in < 35)

System.out.println(“Value of int = ” + in);

}

}

[/code]
Autoboxing and unboxing with method overloading

Autoboxing or unboxing is done in case of method overloading. This happens based on the following rules –

  • Widening beats boxing – When there is a situation to choose between widening and boxing, widening takes the preference – 

Listing4: Sample code showing overloading preference

[code]

public class WideBoxed {    public class WideBoxed {                    static void methodWide(int i) {                                         System.out.println(“int”);                    }                     static void methodWide( Integer i ) {                                         System.out.println(“Integer”);                    }                     public static void main(String[] args) {                                         short shVal = 25;                                         methodWide(shVal);                    }   }}

[/code]

The output of this program is – int

  • Widening beats Varargs – When there is a situation to choose between widening and varargs, widening takes the preference – 

Listing5: Sample code showing overloading preference 

[code]

public class WideVarArgs {

static void methodWideVar(int i1, int i2) {

System.out.println(“int int”);

}

static void methodWideVar(Integer… i) {

System.out.println(“Integers”);

}                public static void main( String[] args) {

short shVal1 = 25;

short shVal2 = 35;

methodWideVar( shVal1, shVal2);

}

}

[/code]

  • Boxing beats Varargs – When there is a situation to choose between boxing and varargs, boxing takes the preference – 

Listing6: Sample code showing overloading preference 

[code]

public class BoxVarargs {

static void methodBoxVar(Integer in) {

System.out.println(“Integer”);

}

static void methodBoxVar(Integer… i) {

System.out.println(“Integers”);

}

public static void main(String[] args) {

int intVal1 = 25;

methodBoxVar(intVal1);

}

}

[/code]

Things to remember in order to use Autoboxing –

As we know that every good feature comes with some drawbacks, Autoboxing is not an exception in this regard. Some important bullets which a developer should keep in mind while using this feature are as under –

  • Comparing objects with equality operator – The equality operator – ‘==’ leads to confusion as it can be applied to both primitive data types and the object. When the operator is applied on objects, it actually compares the reference of the objects and not the values.

Listing7: Sample code showing comparison

[code]

public class Comparator {

public static void main(String[] args) {

Integer istInt = new Integer(1);

Integer secondInt = new Integer(1);

if (istInt == secondInt) {

System.out.println(“both one are equal”);

} else {

System.out.println(“Both one are not equal”);

}

}

}

[/code]

  • Mixing object and primitive in equality and relational operator – If we compare a primitive data type with an object, then the unboxing occurs which may throw a NullPointerException if the object is null.
  • Cached Object – Since the valueOf()method is used to create boxed primitive objects, the used objects are cached. Since java caches integers from -128 to 128, these cached objects may behave differently.
  • Performance degradation – Autoboxing or unboxing degrades the performance of an application as it creates an unwanted object which leads the GC to run more frequently. 

Disadvantage of Autoboxing

Though autoboxing has several advantages, it has the following disadvantage –

  • If autoboxing happens within a loop unnecessary objects gets created and it may slow down the performance of the application. Consider the following code –

Listing8: Sample code showing performance issue

[code]

public int sumEvenNumbers(List<Integer> intList) {    int sum = 0;    for (Integer i: intList)        if ( i % 2 == 0 )            sum += i;        return sum;}

[/code]

In this piece of code, [code] sum += i;  [/code] will expand as [code] sum = sum + i;  [/code]. Since the ‘+’ operation cannot be done on Integer object, the JVM triggers the unboxing of sum Integer Object and then the result is autoboxed back.

  • Prior to jdk 1.5, data types int and Integer were distinct and in case of method overloading these two types were used without any hassle. Now with autoboxing and unboxing, this has become trickier. An example of this is the overloaded remove method in ArrayList. Class ArrayList has two remove methods – remove (index) and remove (object). In this case, method overloading will not happen and the respective method will be called with appropriate parameters. 

Conclusion

Autoboxing is the mechanism to covert a primitive data type into respective wrapper or Object. Compiler uses valueOf() method to convert primitive to Object and uses intValue(), doubleValue() etc to get primitive value from Object. In autoboxing, a boolean is converted to Boolean, byte to Byte, char to Character, float changes to Float, int goes to Integer, long goes to Long and short converts to Short, while in unboxing the conversion happens in the reverse direction.

Tagged on: , ,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share