What is the difference between Boxing and AutoBoxing in Java?
Asked Answered
A

4

8

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?

Amend answered 24/11, 2015 at 14:4 Comment(2)
@Tunaki Well, not necessarily. This could be considered boxing: Integer i = new Integer(1); and this autoboxing Integer i = 1;. However that's just irrelevant semantics.Interface
Autoboxing is automatic boxing, right? You can box an int manually using Integer.valueOf, or you can assign your int value to an Integer variable and it will be autoboxed.Redundant
V
15

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.

Vinitavinn answered 24/11, 2015 at 14:8 Comment(0)
W
7

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;
Windbroken answered 24/11, 2015 at 14:7 Comment(0)
K
0

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.

Source

Kit answered 24/11, 2015 at 14:8 Comment(0)
R
0
  • 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.
Rudie answered 24/11, 2015 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.