Can I get Integer or int after putting int into array of objects?
Yes and yes.
You cannot put int
in Object[]
. What you are doing is using a Java feature called autoboxing, where the primitive type of the type is int
automatically promoted to the appropriate wrapper class ( Integer
in this case) or vice versa as needed.
You can read more about this here .
Edit:
As Jesper points out in the comment below, the answer to your first question is not really "yes," but "it depends on meaning a
." The call to the constructor Integer(int)
, as in (2), will always result in the creation of a new object Integer
and its input into the array.
In (1), however, the autoboxing process will not use this constructor; it will essentially call Integer.valueOf(a)
. This can create a new object Integer
or it can return an already existing cached object Integer
to save time and / or memory depending on the value a
. In particular, values between -128 and 127 are cached.
In most cases, this will not make a significant difference, since objects are Integer
immutable. If you create a very large number of objects Integer
(well over 256 of them) and most are between -128 and 127, your example (1) is likely to be faster and uses less memory than (2).
a source to share