AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardjavaautoboxing

~105s

Comparing boxed integers

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));
    }
}
Show the answer and the worked solution

Correct answer: B.

true false

Worked solution

  1. Assigning an int literal to an Integer calls Integer.valueOf, which caches objects for values from -128 to 127.
  2. Both 127 assignments therefore hand back the very same cached object, so a == b is true.
  3. 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.

Comparing boxed integers — Aptitude Question

Comparing boxed integers: What does this Java program print? Answer and worked solution on CodeKairo.

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

  1. true true
  2. true false
  3. false true
  4. false false
Show the answer and the worked solution

Correct answer: B. true false

Worked solution

  1. Assigning an int literal to an Integer calls Integer.valueOf, which caches objects for values from -128 to 127.
  2. Both 127 assignments therefore hand back the very same cached object, so a == b is true.
  3. 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