Java Primitive Types: int vs. Integer
Short answer: An int
is a number; an Integer
is a pointer that can reference an object that contains a number. Using Integer
for arithmetic involves more CPU cycles and consumes more memory. An int
is not an object and cannot passed to any method that requires objects (just like what you said about Generics).
Non-primitive types are objects. They have to be dynamically allocated, garbage collected, and checked for null-ness (although some of these operations may get removed by an optimizing compiler). Reading their actual value requires loading from a pointer. Primitive types are values. They generally take up less space and are faster to access.
A good rule of thumb is, use primitive types unless you need polymorphism, in which case use the corresponding object.
There is a slight penalty for converting between the types (autoboxing). Also int
will have a bit less overhead so I would always go with int
if you can.
Also see this question: When to use primitive and when reference types in Java