What is autoboxing and unboxing in Java?

Autoboxing & unboxing

Autoboxing & unboxing

Преглед: 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.

Увод
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

[код]

Integer integer = 9;

[/код]

unboxing

[код]

int in = 0;

in = new Integer(9);

[/код]

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 –

Листинг1: Sample code showing Autoboxing

[код]

public int sumEvenNumbers(List<Integer> intList ) { int sum = 0; за (Integer i: intList ) ако ( ја % 2 == 0 ) sum = i; return sum;}

[/код]

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 –

Листинг2: Sample code showing Unboxing

[код]

import java.util.ArrayList;import java.util.List; public class UnboxingCheck { публиц статиц воид маин(Ниска[] аргс) { Integer in = new Integer(-8); // 1. Unboxing through method invocation int absVal = absoluteValue( in ); Систем.оут.принтлн( “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); Систем.оут.принтлн( “phi = ” + phi ); } public static int absoluteValue( int i ) { return (ја < 0) ? -ја : ја; }}

[/код]

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
инт 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 –

Листинг3: Sample code showing Autoboxing and unboxing using comparison operators

[код]

public class BoxedComparator {

публиц статиц воид маин(Ниска[] аргс) {

Integer in = new Integer(25);

ако (in < 35)

Систем.оут.принтлн(“Value of int = ” + in);

}

}

[/код]
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

[код]

public class WideBoxed { public class WideBoxed { static void methodWide(int i) { Систем.оут.принтлн(“инт”); } static void methodWide( Integer i ) { Систем.оут.принтлн(“Integer”); } публиц статиц воид маин(Ниска[] аргс) { short shVal = 25; methodWide(shVal); } }}

[/код]

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

[код]

public class WideVarArgs {

static void methodWideVar(int i1, int i2) {

Систем.оут.принтлн(“int int”);

}

static void methodWideVar(Integer… ја) {

Систем.оут.принтлн(“Integers”);

} публиц статиц воид маин( Ниска[] аргс) {

short shVal1 = 25;

short shVal2 = 35;

methodWideVar( shVal1, shVal2);

}

}

[/код]

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

Listing6: Sample code showing overloading preference

[код]

public class BoxVarargs {

static void methodBoxVar(Integer in) {

Систем.оут.принтлн(“Integer”);

}

static void methodBoxVar(Integer… ја) {

Систем.оут.принтлн(“Integers”);

}

публиц статиц воид маин(Ниска[] аргс) {

int intVal1 = 25;

methodBoxVar(intVal1);

}

}

[/код]

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

[код]

public class Comparator {

публиц статиц воид маин(Ниска[] аргс) {

Integer istInt = new Integer(1);

Integer secondInt = new Integer(1);

ако (istInt == secondInt) {

Систем.оут.принтлн(“both one are equal”);

} else {

Систем.оут.принтлн(“Both one are not equal”);

}

}

}

[/код]

  • 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

[код]

public int sumEvenNumbers(List<Integer> intList) { int sum = 0; за (Integer i: intList) ако ( ја % 2 == 0 ) sum = i; return sum;}

[/код]

In this piece of code, [код] sum = i; [/код] will expand as [код] sum = sum + ја; [/код]. 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.

Закључак

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.

Таггед на: , ,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share