Repaso
EspaƱol
Java CoreIntermediateJV-15

What does this print?

Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println((a == b) + " " + (c == d));

Options

  1. true true
  2. true false (Correct option)
  3. false false
  4. 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().

Key terms

Practice this question in Repaso