What does this print?
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println((a == b) + " " + (c == d));Options
- true true
- true false (Correct option)
- false false
- false true
Answer
true false
Why
When you write Integer a = 127, Java does autoboxing: it calls Integer.valueOf(127). To save memory, valueOf keeps a cache of Integer objects for -128 to 127 and reuses them.
So 127 gives the same object both times (== true), but 128 creates two different objects (== false).
Lesson: never compare wrapper objects with ==; use .equals().
Remember
Integer cache covers -128..127: compare wrappers with equals().