Java - What is the output: AutoBoxing/Unboxing and Integer.valueOf

Question

Consider the following snippet of code.

Integer aaa = 100; // Boxing - Integer.valueOf(100)
Integer bbb = 100; // Boxing - Integer.valueOf(100)
Integer ccc = 505; // Boxing - Integer.valueOf(505)
Integer ddd = 505; // Boxing - Integer.valueOf(505)
System.out.println(aaa == bbb); 
System.out.println(aaa == ccc);
System.out.println(ccc == ddd);

What is the output:



Click to view the answer

System.out.println(aaa == bbb); // will print true
System.out.println(aaa == ccc); // will print false
System.out.println(ccc == ddd); // will print false

Note

For all values between -128 and 127, the Integer class caches Integer object references.

The cache is used when you call its valueOf() method.

If you call Integer.valueOf(100) twice, you get the reference of the same Integer object from the cache that represents the int value of 100.

If you call Integer.valueOf(n - where n is outside the range -128 to 127), a new object is created for every call.

Byte, Short, Character and Long classes also cache object references for values in the range -128 to 127.

Demo

public class Main {
  public static void main(String[] args) {
    Integer aaa = 100; // Boxing - Integer.valueOf(100)
    Integer bbb = 100; // Boxing - Integer.valueOf(100)
    Integer ccc = 505; // Boxing - Integer.valueOf(505)
    Integer ddd = 505; // Boxing - Integer.valueOf(505)
    System.out.println(aaa == bbb); 
    System.out.println(aaa == ccc);
    System.out.println(ccc == ddd);
  }/*from  w w w  .j av  a  2  s  . c om*/

}

Result

Related Quiz