Which one is best in programming – int or Integer? Especially whenever both are doing the same task?
I am writing an application in Java. In most of the places of primitive data types, I use int; and for objects, I use Integer. So I am confused- which one is the best in places, where we have to use objects.
According to performance, which one is best for a Java application?
Use
intwhen possible, and useIntegerwhen needed. Sinceintis a primitive, it will be faster. Modern JVMs know how to optimizeIntegers using auto-boxing, but if you’re writing performance critical code,intis 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
intwhenever 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.