0

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` is incorrect because generic types `<..>` can't use primitives. – Pshemo Apr 15 '14 at 19:35

2 Answers2

4

int is primitive data type where is Integer is a wrapper 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. An int 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

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
0

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 Collections, 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.

BlairHippo
  • 9,502
  • 10
  • 54
  • 78