Java reference equality and equals on the same object: compute the final result value printed. public class ObjComp { public static void main(String [] args ) { int result = 0; ObjComp oc = new ObjComp(); Object o = oc; if (o == oc) result = 1; if (o != oc) result = result + 10; if (o.equals(oc)) result = result + 100; if (oc.equals(o)) result = result + 1000; System.out.println("result = " + result); } }
-
A1
-
B10
-
C101
-
D1101
-
E1001
Answer
Correct Answer: 1101
Explanation
Introduction / Context: This program compares an object reference and another reference to the same object using both identity (==, !=) and value equality (equals). Because equals inherits from Object and both references point to the same instance, all equals checks are true and identity equality is also true.
Given Data / Assumptions:
- o and oc refer to the very same instance.
- Object.equals defaults to identity unless overridden; here, ObjComp does not override equals.
- We sum flags into result depending on each check’s outcome.
Concept / Approach: Identity check: (o == oc) is true, (o != oc) is false. Equals: o.equals(oc) and oc.equals(o) both evaluate to true because both references are identical, so Object.equals returns true in both directions.
Step-by-Step Solution: Start result = 0. (o == oc) → true → result = 1. (o != oc) → false → no change. o.equals(oc) → true → result = 1 + 100 = 101. oc.equals(o) → true → result = 101 + 1000 = 1101. Printed: "result = 1101".
Verification / Alternative check: If o referenced a different ObjComp instance, identity would be false and equals would also be false (since equals is not overridden), yielding 0.
Why Other Options Are Wrong: 1, 10, 101 omit one or more true conditions; only 1101 includes all correct increments.
Common Pitfalls: Assuming equals is always overridden to compare state; conflating identity and equality.
Final Answer: 1101