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. δηλ. 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;import java.util.List; public class UnboxingCheck { δημόσια στατική άκυρη κύρια(Κορδόνι[] args) { Integer in = new Integer(-8); // 1. Unboxing through method invocation int absVal = absoluteValue( σε ); System.out.println( “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); System.out.println( “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 {

δημόσια στατική άκυρη κύρια(Κορδόνι[] args) {

Integer in = new Integer(25);

αν (σε < 35)

System.out.println(“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) { System.out.println(“int”); } static void methodWide( Integer i ) { System.out.println(“Integer”); } δημόσια στατική άκυρη κύρια(Κορδόνι[] args) { 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) {

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

}

static void methodWideVar(Integer… εγώ) {

System.out.println(“Integers”);

} δημόσια στατική άκυρη κύρια( Κορδόνι[] args) {

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) {

System.out.println(“Integer”);

}

static void methodBoxVar(Integer… εγώ) {

System.out.println(“Integers”);

}

δημόσια στατική άκυρη κύρια(Κορδόνι[] args) {

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 {

δημόσια στατική άκυρη κύρια(Κορδόνι[] args) {

Integer istInt = new Integer(1);

Integer secondInt = new Integer(1);

αν (istInt == secondInt) {

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

} αλλού {

System.out.println(“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 (αντικείμενο). Σε αυτήν την περίπτωση, 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