Search code examples
javaboxing

What is the difference between Boxing and AutoBoxing in Java?


What is the difference between Boxing and AutoBoxing in Java? Several Java Certification books use two such terms. Do they refer to the same thing that is Boxing?


Solution

  • Boxing is the mechanism (ie, from int to Integer); autoboxing is the feature of the compiler by which it generates boxing code for you.

    For instance, if you write in code:

    // list is a List<Integer>
    list.add(3);
    

    then the compiler automatically generates the boxing code for you; the "end result" in code will be:

    list.add(Integer.valueOf(3));
    

    A note about why Integer.valueOf() and not new Integer(): basically, because the JLS says so :) Quoting section 5.1.7:

    If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

    And you cannot enforce this requirement if you use a "mere" constructor. A factory method, such as Integer.valueOf(), can.