I was wondering what the difference between the variable type 'int' and the variable type 'Integer' and what the uses of using both is. Thanks!
-
Ask Google, he is a good guy. – Salah Apr 15 '14 at 19:28
-
Additional info to answers: one of cases where you have to use `Integer` instead of `int` is when you need to specify generic type for integers like list of integers declared as `List
` is correct while `List – Pshemo Apr 15 '14 at 19:35` is incorrect because generic types `<..>` can't use primitives.
2 Answers
int
isprimitive data type
where isInteger
is awrapper class
(an Object).
If you need an object then Integer
comes into picture and other int
you know it already.
All the Collection
class accepts only object in that case you can't use simple int primitive data type.
An
int
is a primitive. It is not an Object. Anint
is a high performance, streamlined beast for calculating numbers.An
Integer
, is an Object that contains a single int field. An Integer is much bulkier than an int. It is sort like a box to contain the int.
For more info look at Primitive Data Types and Primitive wrapper class
In practical terms, it often boils down to whether you want to have null
as a potential value for your variable. Spoiler: You probably don't. Though if you're handling data going into/coming out of a database, null
suddenly becomes a legitimate data condition and not just a null-pointer error waiting to happen. (Though you have to code very defensively when null
is in the mix.)
Some very useful objects, like Collection
s, will only work on other objects and not primitives. That's another place where you'd want to use the object rather than the primitive, though when actually working with the data, I generally recommend converting it to a primitive at your first opportunity.

- 9,502
- 10
- 54
- 78