Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Autoboxing and unboxing in Java

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

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:

Listing 1: Sample code showing Autoboxing

public int sumEvenNumbers(List<Integer> intList ) {
    int sum = 0;
    for (Integer i: intList )
        if ( i % 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:

Listing 2: Sample code showing Unboxing

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;
	}
}

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:

Listing 3: Sample code showing Autoboxing and unboxing using comparison operators

public class BoxedComparator {
	public static void main(String[] args) {
		Integer in = new Integer(25);
		if (in < 35)
			System.out.println("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:

Listing 4: 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");
	}

	public static void main(String[] 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

Listing 5: Sample code showing overloading preference

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);
	}
}
  • Boxing beats Varargs - When there is a situation to choose between boxing and varargs, boxing takes the preference

Listing 6: Sample code showing overloading preference

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);
	}
}

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.

Listing 7: Sample code showing comparison

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");
		}
	}
} 
  • 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:

Listing 8: Sample code showing performance issue

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

In this piece of code, sum += i; will expand as sum = sum + i; . 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.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login