I am confused about when to use primitive vs. non-primitive(?) types (i.e. int vs. Integer) in Java. I realize that in some places you can't use primitive types (for example when making use of generics). But what about in "normal" code? Is there a performance penalty for using non-primitive types? What about when working with Android?
***My question is very similar to this question, which was discovered by one of the posters below. The answers to the linked question give additional insights into this question, which are not covered below.
*** "non-primitive" types are officially referred to as reference types.
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.
What is the difference between int[] a and int a[] in Java? There is no difference in these two types of array declaration. There is no such difference in between these two types of array declaration. It's just what you prefer to use, both are integer type arrays.
Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster.
Short answer: An int
is a number; an Integer
is a pointer that can reference an object that contains a number. Using Integer
for arithmetic involves more CPU cycles and consumes more memory. An int
is not an object and cannot passed to any method that requires objects (just like what you said about Generics).
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