I came across a class using Integer variables to capture size to be used in a for loop. Is this good practice or should we use the int primitive data type?
Integer size = something.getFields().size(); for (Integer j = 0; j < size - 1; ++j)
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.
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.
The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type. An int is a data type that stores 32-bit signed two's complement integer whereas an Integer is a class that wraps a primitive type int in an object.
Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster.
the Integer class is provided so that values can be boxed/unboxed in a pure OO manner. use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.
Java Int vs Integer
However, very different things are going on under the covers here. An int is a number; an > Integer is a pointer that can reference an object that contains a number.
...
An int is not an object and cannot passed to any method that requires objects. A common case is in using the provided collection classes ( List , Map , Set ) - though it is possible to write versions of these classes that provide similar capabilities to the object versions. The wrapper classes ( Integer , Double , etc) are frequently required whenever introspection is used (such as in the reflection API).
A better description of when to use one vs. the other:
Choosing between int and Integer
I'll start with how these types should be used before going into detail on why.
- Prefer
int
for performance reasons- Methods that take objects (including generic types like
List<T>
) will implicitly require the use of Integer- Use of
Integer
is relatively cheap for low values (-128 to 127) because of interning - useInteger.valueOf(int)
and not new Integer(int)- Do not use
==
or!=
with Integer types- Consider using
Integer
when you need to represent the absence of a value (null)- Beware unboxing Integer values to int with null values
If you can use int
do so. If the value can be null
or is used as an Object e.g. Generics, use Integer
Usually it doesn't matter which one you use but often int
performs slightly better.
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