nerdexam
Oracle

1Z0-808 · Question #34

public class Product { int id; String name; public Product (int id, String name) { this.id = id; this.name = name; } } And given the code fragment: 4. Product p1 = new Product (101, "Pen"); 5…

The correct answer is C. false:true. Option C is correct because p1 == p2 compares object references, not content - p1 and p2 point to two separate Product objects in memory (created on lines 4 and 5), so == returns false. However, p1.name.equals(p2.name) compares the String values "Pen" and "Pen", which are…

Java Basics

Question

public class Product { int id; String name; public Product (int id, String name) { this.id = id; this.name = name; } } And given the code fragment: 4. Product p1 = new Product (101, "Pen"); 5. Product p2 = new Product (101, "Pen"); 6. Product p3 = p1; 7. boolean ans1 = p1 == p2; 8. boolean ans2 = p1.name.equals (p2.name); 9. System.out.print (ans1 + ":" + ans2); What is the result?

Options

  • Atrue:true
  • Btrue:false
  • Cfalse:true
  • Dfalse:false

How the community answered

(29 responses)
  • A
    14% (4)
  • B
    7% (2)
  • C
    76% (22)
  • D
    3% (1)

Explanation

Option C is correct because p1 == p2 compares object references, not content - p1 and p2 point to two separate Product objects in memory (created on lines 4 and 5), so == returns false. However, p1.name.equals(p2.name) compares the String values "Pen" and "Pen", which are identical, so .equals() returns true, giving output false:true.

Why distractors fail:

  • A (true:true) - p1 == p2 can't be true because they are distinct objects; only p1 == p3 would be true (same reference, line 6).
  • B (true:false) - wrong on both sides; == is false and .equals() is true.
  • D (false:false) - gets == right but incorrectly assumes .equals() on two identical Strings returns false.

Memory tip: Think of == as asking "same house?" (same memory address) and .equals() as asking "same contents?" - two houses can look identical inside while still being different houses.

Topics

#Reference Equality#equals() method#== operator#Object Identity

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice