1Z0-803 · Question #125
Given: class Prime { int num; Prime(int num) { this.num = num; } } public class Test { public static void main (String[] args) { Prime obj1 = new Prime(13); Prime obj2 = new Prime(13); if (obj1 == obj
The correct answer is D. Not equal. This code compares two distinct Prime objects using both the '==' operator for reference comparison and the default Object.equals() method.
Question
Given:
class Prime { int num; Prime(int num) { this.num = num; } } public class Test { public static void main (String[] args) { Prime obj1 = new Prime(13); Prime obj2 = new Prime(13); if (obj1 == obj2) { System.out.println("Equal"); } else { System.out.println("Not equal"); } if (obj1.equals(obj2)) { System.out.println("Equal"); } else { System.out.println("Not equal"); } } } What is the result?
Options
- AEqual
- BNot equal
- CEqual
- DNot equal
How the community answered
(42 responses)- A5% (2)
- B10% (4)
- C14% (6)
- D71% (30)
Why each option
This code compares two distinct Prime objects using both the '==' operator for reference comparison and the default Object.equals() method.
'Equal' is incorrect because object references obj1 and obj2 point to different memory locations, making obj1 == obj2 false.
'Equal' is incorrect because the Prime class does not override the equals() method, so it defaults to Object.equals(), which also performs a reference comparison, thus obj1.equals(obj2) is false.
Both obj1 == obj2 and obj1.equals(obj2) evaluate to false because new Prime(13) creates two separate objects in memory, meaning their references are different and the default equals() method also performs reference comparison. Therefore, both conditional blocks print 'Not equal'.
Concept tested: Java object reference and default equals() comparison
Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)
Topics
Community Discussion
No community discussion yet for this question.