Which one is best in programming - int
or Integer
? Especially whenever both are doing the same task?
I am writing an appli
As an alternative view.... perhaps you should use neither Integer nor int.
If the value is really an object with behaviour - like say an amount of money, or a distance or something, then perhaps you should be using an object with behaviour.
You can see more about this kind of thing here:
http://www.time4tea.net/wiki/display/MAIN/Microtypes
Although this may be "slower", the additional type safety will make the programming, testing and debugging of your system much easier & faster.
Use int
wherever possible. Use Integer
only if:
Integer
can be null
, an int
always has an int value.List
(though you can use int
externally and have autoboxing hide the fact that the collection internally stores Integer
instances).Integer
or Object
, or doesn't work with primitive types.int is primitive, Integer is an int wrapped up as an object.
It really depends how you are going to be using them.
int
a primitive, typically it should be faster. It just carries the raw number data.
Integer
is an object, it carries some extra stuff so you e.g. can put the number in lists.
Use int
when possible, and use Integer
when needed. Since int
is a primitive, it will be faster. Modern JVMs know how to optimize Integer
s using auto-boxing, but if you're writing performance critical code, int
is the way to go.
Take a look at this and this article. Although you shouldn't treat them as absolute truths, they do show that objects will be slower than their primitive counterparts.
So, use int
whenever possible (I will repeat myself: if you're writing performance critical code). If a method requires an Integer, use that instead.
If you don't care about performance and want to do everything in an object oriented fashion, use Integer
.