Java Language Using int and Integer interchangeably

Download Java Language for free

Example

As you use generic types with utility classes, you may often find that number types aren't very helpful when specified as the object types, as they aren't equal to their primitive counterparts.

List<Integer> ints = new ArrayList<Integer>();
Java SE 7
List<Integer> ints = new ArrayList<>();

Fortunately, expressions that evaluate to int can be used in place of an Integer when it is needed.

for (int i = 0; i < 10; i++)
    ints.add(i);

The ints.add(i); statement is equivalent to:

ints.add(Integer.valueOf(i));

And retains properties from Integer#valueOf such as having the same Integer objects cached by the JVM when it is within the number caching range.

This also applies to:

  • byte and Byte
  • short and Short
  • float and Float
  • double and Double
  • long and Long
  • char and Character
  • boolean and Boolean

Care must be taken, however, in ambiguous situations. Consider the following code:

List<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.remove(1); // ints is now [1, 3]

The java.util.List interface contains both a remove(int index) (List interface method) and a remove(Object o) (method inherited from java.util.Collection). In this case no boxing takes place and remove(int index) is called.

One more example of strange Java code behavior caused by autoboxing Integers with values in range from -128 to 127:

Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b); // true
System.out.println(c <= d); // true
System.out.println(c >= d); // true
System.out.println(c == d); // false

This happens because >= operator implicitly calls intValue() which returns int while == compares references, not the int values.

By default, Java caches values in range [-128, 127], so the operator == works because the Integers in this range reference to the same objects if their values are same. Maximal value of the cacheable range can be defined with -XX:AutoBoxCacheMax JVM option. So, if you run the program with -XX:AutoBoxCacheMax=1000, the following code will print true:

Integer a = 1000;
Integer b = 1000;
System.out.println(a == b); // true
Basic Control Structures