Let's say that I have a class:
class A {
private Integer i;
public int getI() {
return i;
}
// Setter, etc.
}
and I write:
A a = // initializer
Integer b = a.getI();
how many Integers will there be? My naive reading about autoboxing/unboxing leads me to believe that the answer is 2, but if getI() were:
public Integer getI();
then the answer would be 1.
You are absolutely correct, with one caveat: the answer to the first part depends on the value of
Integer i
.Integer
is created in the constructor, and the other one is created when boxing theint
coming fromgetI()
Integer
object.Note: if the value of the
Integer i
is small (more precisely, between -128 and 127, inclusive), autoboxing will produce the sameInteger
through interning.