nerdexam
Oracle

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.

Working with Java Data Types

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)
  • A
    5% (2)
  • B
    10% (4)
  • C
    14% (6)
  • D
    71% (30)

Why each option

This code compares two distinct Prime objects using both the '==' operator for reference comparison and the default Object.equals() method.

AEqual

'Equal' is incorrect because object references obj1 and obj2 point to different memory locations, making obj1 == obj2 false.

BNot equal
CEqual

'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.

DNot equalCorrect

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

#object equality#reference comparison#equals method#constructors

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice