Comparing boxed integers — Aptitude Question
Comparing boxed integers: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 105 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println((a == b) + " " + (c == d));
}
}Options
- true true
- true false
- false true
- false false
Show the answer and the worked solution
Correct answer: B. true false
Worked solution
- Assigning an int literal to an Integer calls Integer.valueOf, which caches objects for values from -128 to 127.
- Both 127 assignments therefore hand back the very same cached object, so a == b is true.
- 128 lies outside the cache, so two distinct objects are created and c == d is false, giving true false.
Answer: true false.
The idea
Boxed types compare by reference under ==, and the small-value cache makes that behaviour look inconsistent. Comparing with equals, or unboxing to int first, is the reliable route.
Shortcut. Integer.valueOf caches −128 to 127: 127 sits inside the cache (same object, true) and 128 just outside it (two objects, false).
Common trap. "true true" assumes == on Integer compares values as it does on int; it compares references, and only the cached range shares them.
All Programming Fundamentals questions · placement mock tests