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 –

Listing1: Sample code showing Autoboxing

[קוד]

public int sumEvenNumbers(רשימה<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 –

Listing2: Sample code showing Unboxing

[קוד]

import java.util.ArrayList;ייבוא ​​java.util.List; public class UnboxingCheck { הריק סטטי הראשי ציבורי(חוט[] ארגומנטים) { Integer in = new Integer(-8); // 1. Unboxing through method invocation int absVal = absoluteValue( ב ); שיטה( “absolute value of ” + ב + ” = ” + absVal ); רשימה<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
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

[קוד]

public class BoxedComparator {

הריק סטטי הראשי ציבורי(חוט[] ארגומנטים) {

Integer in = new Integer(25);

אם (ב < 35)

שיטה(“Value of int = ” + ב);

}

}

[/קוד]
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) { שיטה(“int”); } 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”);

} אַחֵר {

שיטה(“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(רשימה<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