In which case should you use primitive types(int
) or reference types (Integer
)?
This question sparked my curiosity.
Variables in Java are classified into primitive and reference variables. From the programmer's perspective, a primitive variable's information is stored as the value of that variable, whereas a reference variable holds a reference to information related to that variable.
The main reason primitive data type are there because, creating object, allocating heap is too costly and there is a performance penalty for it. As you may know primitive data types like int, float etc are most used, so making them as Objects would have been huge performance hit.
In which case should you use primitive types(
int
) or reference types (Integer
)?
As a rule of thumb, I will use a primitive (such as int
) unless I have to use a class that wraps a primitive.
One of the cases were one must use a wrapper class such as Integer
is in the case of using generics, as Java does not support the use of primitive types as type parameters:
List<int> intList = new ArrayList<int>(); // Not allowed. List<Integer> integerList = new ArrayList<Integer>(); // Allowed.
And, in many cases, I will take advantage of autoboxing and unboxing, so I don't have to explicitly perform conversions from primitives to its wrapper class and vice versa:
// Autoboxing will turn "1", "2", "3" into Integers from ints. List<Integer> numbers = Arrays.asList(1, 2, 3); int sum = 0; // Integers from the "numbers" List is unboxed into ints. for (int number : numbers) { sum += number; }
Also, as an additional note, when converting from primitives to its wrapper class objects, and unique instances of objects are not necessary, use the valueOf
method provided by the wrapper method, as it performs caching and return the same instance for a certain value, reducing the number of objects which are created:
Integer i1 = Integer.valueOf(1); // Prefer this. Integer i2 = new Integer(1); // Avoid if not necessary.
For more information on the valueOf
methods, the API specification for the Integer.valueOf
method can serve as a reference for how those methods will behave in the wrapper classes for primitives.
That really depends on the context. First prefer the primitive, because it's more intuitive and has less overhead. If it is not possible for generics/autoboxing reasons, or if you want it to be nullable, then go for the wrapper type (complex type as you call it).
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