In Java (wrapper equality and autoboxing nuances), what is the final printed value of result for the following program? public class WrapTest { public static void main(String [] args) { int result = 0; short s = 42; Long x = new Long("42"); Long y = new Long(42); Short z = new Short("42"); Short x2 = new Short(s); Integer y2 = new Integer("42"); Integer z2 = new Integer(42); if (x == y) /* Line 13 */ result = 1; if (x.equals(y) ) /* Line 15 */ result = result + 10; if (x.equals(z) ) /* Line 17 */ result = result + 100; if (x.equals(x2) ) /* Line 19 */ result = result + 1000; if (x.equals(z2) ) /* Line 21 */ result = result + 10000; System.out.println("result = " + result); } }

Difficulty: Medium

Correct Answer: result = 10

Explanation:


Introduction / Context:
This question tests how Java wrapper objects compare using reference equality (==) versus value equality (equals), and how equals enforces exact wrapper types. It also reinforces that new Long(...) always creates distinct objects, so reference comparisons commonly fail even when values are the same.


Given Data / Assumptions:

  • x = new Long("42") and y = new Long(42) produce two different Long objects that both hold the value 42.
  • z and x2 are Short instances with value 42; y2 and z2 are Integer instances with value 42.
  • result starts at 0, and increments depend on conditions using == and equals.


Concept / Approach:
In Java, == on objects checks reference identity, not numeric value. equals on wrapper types checks both the numeric value and the exact wrapper class (e.g., Long.equals requires the other object to be Long). There is no cross-wrapper numeric coercion inside equals.


Step-by-Step Solution:

if (x == y): two distinct Long objects → false → result stays 0 if (x.equals(y)): same value and same wrapper type → true → result = 10 if (x.equals(z)): Long vs Short → false → result = 10 if (x.equals(x2)): Long vs Short → false → result = 10 if (x.equals(z2)): Long vs Integer → false → result = 10


Verification / Alternative check:
Replace new Long(42) with Long.valueOf(42) and interning may still not help for == because Long caches only in the range -128..127 for valueOf, but two separate new calls never share the same reference.


Why Other Options Are Wrong:

  • 1 or 11: would require x == y to be true or some cross-wrapper equals to succeed.
  • 11010 or 10010: would require equals(Long, Short/Integer) to return true, which it cannot.


Common Pitfalls:
Expecting autoboxing or numeric promotion to apply inside equals across wrapper classes; equals is strict about the runtime type.


Final Answer:
result = 10

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion