Predict the output · Java

Integer Cache and ==

Easy Predict the output Most askedSeen at Amazon, Oracle, Goldman Sachs

What does this print?

What does this print?

public class Main {
    public static void main(String[] args) {
        Integer a = 127, b = 127, c = 128, d = 128;
        System.out.println(a == b);
        System.out.println(c == d);
        System.out.println(c.equals(d));
    }
}
  1. true
    true
    true
  2. true
    false
    true
  3. false
    false
    true
  4. true
    false
    false

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

true
false
true

Autoboxing uses Integer.valueOf, which caches values from −128 to 127. a and b are the same cached object, so == (reference comparison) is true; 128 creates two distinct objects, so c == d is false. equals compares values. Always compare boxed numbers with equals (or unbox).