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?
In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.
Even though improvements have been made in later Java implementations, arithmetic operations using Integer can be several (2 or more) times slower than the same operations using a primitive int, so if you're going to be doing many calculations and fast execution time is critical, consider using int instead of Integer.
int provides less flexibility as compare to Integer as it only allows binary value of an integer in it. Integer on other hand is more flexible in storing and manipulating an int data. Since Wrapper classes inherit Object class, they can be used in collections with Object reference or generics.
Primitive type int needs 4 bytes in Java but, Integer object occupies 16 bytes of memory. Hence, int is comparatively faster than an Integer object. Since, int is a primitive type it is less flexible. We can only store the binary value of an integer in it.
Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster. Modern JVMs know how to optimize Integers 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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With