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?
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.
In my understanding, "Boxing" means "explicitly constructing a wrapper around a primitive value". For example:
int x = 5;
Integer y = new Integer(x); //or Integer.valueOf(x);
Meanwhile, "Autoboxing" means "implicitly constructing a wrapper around a primitive value". For example:
Integer x = 5;
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
- Unboxing is the conversion from the wrapper-class to the primitive datatype. Eg. when you pass an Integer when an int is expected.
- Autoboxing is the automatic conversion from a primitive datatype into to its corresponding wrapper-class. Eg. when you pass an int when an Integer object is expected.
© 2022 - 2024 — McMap. All rights reserved.
Integer i = new Integer(1);
and this autoboxingInteger i = 1;
. However that's just irrelevant semantics. – Interfaceint
manually usingInteger.valueOf
, or you can assign yourint
value to anInteger
variable and it will be autoboxed. – Redundant