The difference between the scalar type int
and the boxed type Integer
is surprising to someone new to Java.
Java has always made a distinction between the "scalar" types, which are not classes: boolean
(true/false), char
(unsigned 16-bit), short
(signed 16-bit), int
(signed 32-bit), and long
(signed 64-bit); and everything else which is a class and ultimately derived from the Object
class.
The problem comes when you want to use something like a generic collection like a List
. A List
can contain anything that is derived from Object
, but not scalar values. So in order to store int
values into a List
, you need to wrap them into an instance of a class called Integer
that is derived from Object
.
In old versions of Java, you also needed to explicitly get the value out of the Integer
class using a .intValue()
method call. In newer versions of Java, this conversion is called "unboxing" and is automatic in some situations.
Sun has a short page about autoboxing which is aimed toward a more experienced programmer but might be informative.