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));
}
}
true true true
true false true
false false true
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).
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium