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:
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:
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:
x == y
to be true or some cross-wrapper equals to succeed.
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
Discussion & Comments