Autoboxing
Home ] Up ] Passing Arguments ] Returning Values ] [ Autoboxing ]

 

 

In Java 5.0, this need for an explicit conversion between a primitive type and its wrapper class has been automated.  The Java 5.0 compiler does automatic "autoboxing" and "unboxing" without you having to do anything explicitly.

For example, the Java 5.0 compiler will "autobox" the integer value in the following code:

package example;

public class PassIntTest
{
  public static void handleValue(Object value)
  {
    // Do something with value...
  }

  public static void main(String[] args)
  {
    int intValue = 56;
    handleValue(intValue);
  }
}

which will compile and run in Java 5.0 and beyond (only).

Similarly, the Java 5.0 compiler will "unbox" the integer value in the following code:

package example;

public class ReturnIntTest
{
  public static Integer returnValue()
  {
    return new Integer(42);
  }

  public static void main(String[] args)
  {
    int intValue = returnValue();
    System.out.println(intValue);
  }
}

It too, will compile and run, but only in Java 5.0 and beyond.

The "autoboxing" and "unboxing" that the compiler performs automatically is entirely equivalent to the manual equivalent that you had to do yourself prior to Java 5.0.

 

This page was last modified on 02 October, 2007