how2examples.com
Home - Introduction to Java Programming

Java Autoboxing

Java 5 introduced autoboxing (also known as auto-unboxing, boxing or unboxing). Autoboxing provides a convenient way to switch between primitive types and wrapper classes without having to explicitly wrap or unwrap them each time.

Assignments

A reference to a wrapper type can be assigned to a variable declared as a primitive type. A primitive variable can be assigned to a wrapper reference variable.

Autoboxing in variable assignments.
Code snippet:
int i = new Integer(5);
Double d = 12.345;
System.out.println(i+" "+d);
Output from running code snippet:
5 12.345

Boolean expressions

You can use a reference to a Boolean wrapper type anywhere a boolean primitive value is expected.

Use of Boolean in boolean expressions.
Code snippet:
Boolean b = true;
if (b) {
   System.out.print("A");
} else {
   System.out.print("B");
}
if (!b) {
   System.out.print("C");
} else {
   System.out.print("D");
}
Output from running code snippet:
AD

Method Arguments and Return Values

If a method takes a wrapper argument type you can pass a primitive of the matching type. If a method takes a primitive you can pass a reference to a wrapper of the matching type.

If a method has a wrapper return type you can return a primitive of the matching type. If a method has a primitive return type you can return a reference to a wrapper of the matching type.

Contents of MethodAutoboxingExample.java:
public class MethodAutoboxingExample{
   public static void main(String[] args) {
      Character c = 'a';
      Boolean b = x(c);
      double d = 56.78;
      int i = y(d);
      System.out.println(b+" "+i);
   }
   
   static boolean x(char c) {
      return Boolean.TRUE;
   }
   
   static Integer y(Double d) {
      return d.intValue();
   }
}
Command to compile MethodAutoboxingExample.java:
javac MethodAutoboxingExample.java
Command to run MethodAutoboxingExample:
java MethodAutoboxingExample
Output from running MethodAutoboxingExample:
true 56

Numeric Operations

You can use a wrapper object in operations where the primitive type is required. This includes using the increment object (++) in an Integer object.

Using a wrapper class in numeric operations.
Code snippet:
Integer i1 = 5;
i1++;
int i2 = i1 + 3;
System.out.println(i1+" "+i2);
Output from running code snippet:
6 9

It is also possible to use wrapper objects with the increment and decrement operators (++ and --). The code may give the impression that you are changing the value of an Integer object but that is not the case. Integer objects are immutable - it is not possible to change the value of an instance. What actually happens when you use an increment operator on a variable of type Integer is that the Integer object is unboxed and the resulting primitive is incremented before being used to create a newInteger that replaces the reference to the original Integer object.

Using a wrapper class in numeric operations.
Code snippet:
Integer i1 = 5;
Integer i2 = 5;
System.out.println(i1+" "+i2+" "+(i1==i2));
int i3 = i2++;
int i4 = ++i2;
System.out.println(i1+" "+i2+" "+i3+" "+i4+" "+(i1==i2));
Output from running code snippet:
5 5 true
5 7 5 7 false

Collections

The data structures in the collections framework deal with the storage and retrieval of objects. Before autoboxing, if you wanted to use primitives with collections you had to explicitly wrap the primitive when storing it and explicitly unwrap it on retrieval. Autoboxing provides a convenient way to store primitives in collections by automatically performing the wrapping and unwrapping.

Description.
Code snippet:
Map<Character, Integer> m = new HashMap<Character, Integer>();
m.put('a', new Integer(456));
m.put(new Character('z'), -2);
int i1 = m.get(new Character('a'));
Integer i2 = m.get('z');
System.out.println(i1+" "+i2);
Output from running code snippet:
456 -2

NullPointerException

If a variable has a value of null then a NullPointerException will be thrown if an attempt is made to use it where unboxing is required.

Attempt to unbox a null reference in a calculation.
Code snippet:
Integer w = null;
int i = 8 + w;
Output from running code snippet:
java.lang.NullPointerException
Attempt to unbox a null reference to use as a method parameter.
Contents of UnboxingNullPointerExceptionExample.java:
public class UnboxingNullPointerExceptionExample {
   public static void main(String[] args) {
      Integer i = null;
      x(i);
   }
   
   static void x(int i) {
      System.out.println(i);
   }
}
Command to compile UnboxingNullPointerExceptionExample.java:
javac UnboxingNullPointerExceptionExample.java
Command to run UnboxingNullPointerExceptionExample:
java UnboxingNullPointerExceptionExample
Output from running UnboxingNullPointerExceptionExample:
Exception in thread "main" java.lang.NullPointerException
   at UnboxingNullPointerExceptionExample.main(UnboxingNullPointerExceptionExample.java:4)
Attempt to unbox a null reference returned by a method.
Code snippet:
Map<Character, Integer> m = new HashMap<Character, Integer>();
int i = m.get('a');
Output from running code snippet:
java.lang.NullPointerException

Converting Between Types

When performing a widening from one primitive type to another (e.g. from an int to a float) there is no need for a cast. When converting a primitive type to a wrapper class of a different primitive type there is always a requirement to cast the primitive first (even when widening).

Attempt to convert an int primitive to a Float object without a cast.
Code snippet:
int i = 9;
Float f = i;
Result of trying to compile code snippet:
incompatible types
found   : int
required: java.lang.Float
Float f = i;
          ^
1 error
Attempt to convert an int primitive to a Float object with an explicit cast.
Code snippet:
int i = 9;
Float f = (float)i;
System.out.println(i+" "+f);
Output from running code snippet:
9 9.0

It also not possible to automatically widen a wrapper object to another wrapper object (e.g. from an Integer to a Float).

Attempt to convert an Integer object to a Float object without a cast.
Code snippet:
Integer i = 9;
Float f = i;
Result of trying to compile code snippet:
incompatible types
found   : java.lang.Integer
required: java.lang.Float
Float f = i;
          ^
1 error
Attempts to convert an Integer object to a Float object with an explicit cast.
Code snippet:
Integer i = 9;
Float f1 = (float) i;
Float f2 = i.floatValue();
Float f3 = new Float(i);
System.out.println(i+" "+f1+" "+f2+" "+f3);
Output from running code snippet:
9 9.0 9.0 9.0

For more information see the rules for method overloading.