Java autoboxing syntax

Java FAQ: Can you provide an example of the Java 5 autoboxing syntax?

Sure. The sample program that follows shows several examples of the Java 5 autoboxing (and unboxing) capability. First, I created a List of integers (Integer), but then, instead of adding Integer references, I add plain old int primitive types. Next, I get those some elements out and treat them again like Integer objects in a Java 5 for-each loop. Finally, I also show that items in the List can be treated as int primitives by doing some basic math, then printing the result value.

package com.devdaily.javasamples;

import java.util.ArrayList;
import java.util.List;

 * A Java autoboxing example
public class JavaAutoboxingExample {

    public static void main(String[] args) {

        List ints = new ArrayList();
        // (1) lets you add int values to a List

        // (2) treat values coming out of the List as Integer references
        for (Integer theInt : ints) {
            // could have called any Integer method here
        // (3) treat values coming out of the List as int values
        int result = ints.get(0) + ints.get(1) + ints.get(2);
        System.out.println("result = " + result);


As Sun (now Oracle) writes, the use of autoboxing and unboxing blurs the distinction between primitives and their corresponding class objects. I generally like this, but you have to keep in mind this warning from Sun on when you should use autoboxing:

"So when should you use autoboxing and unboxing? Use them only when there is an impedance mismatch between reference types and primitives, for example, when you have to put numerical values into a collection.

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it."

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.