ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
Long l = 127L;
Integer i = 127;
System.out.print(l.equals(127) + " ");
System.out.print(l.equals(127L) + " ");
System.out.print((l == 127) + " ");
System.out.print(i.equals(l));
  1. A. true true true false
  2. B. true true true true
  3. C. false true false false
  4. D. false true true false

Correct answer: D. false true true false

equals on wrapper classes first checks the runtime type. l.equals(127) boxes the int 127 to an Integer, which is not a Long, so false. l.equals(127L) compares with a Long of equal value: true. l == 127 compares a Long with an int, which unboxes l and compares numerically: true. i.equals(l) is false for the same type reason. The values are equal everywhere; only the boxed types differ.

More OOP with C++ and Java questions

Exams that ask this topic