Search code examples
javaintegerintprimitive

Using int vs Integer


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) 

Solution

  • 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
    1. because of interning - use Integer.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