the Integer class is provided so that values can be boxed/unboxed in a pure OO manner. use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.
However, very different things are going on under the covers here. An int is a number; an > Integer is a pointer that can reference an object that contains a number.
An int is not an object and cannot passed to any method that requires
objects. A common case is in using the provided collection classes (
List , Map , Set ) – though it is possible to write versions of these
classes that provide similar capabilities to the object versions. The
wrapper classes ( Integer , Double , etc) are frequently required
whenever introspection is used (such as in the reflection API).
A better description of when to use one vs. the other:
Choosing between int and Integer
I’ll start with how these types should be used before going into
detail on why.
intfor performance reasons
- Methods that take objects (including generic types like
will implicitly require the use of
- Use of
Integeris relatively cheap for low values (-128 to
- because of interning – use
Integer.valueOf(int)and not new
- Do not use
!=with Integer types
- Consider using
Integerwhen you need to represent the
absence of a value (null)
- Beware unboxing Integer values to int with null values