nerdexam
Oracle

1Z0-829 · Question #45

Given the code fragment: Pet p = new Pet("Dog"); Pet p1 = p; p1.name = "Cat"; p = p1; System.out.println(p.name); p = null; System.out.println(p1.name); What is the result?

The correct answer is D. Cat Cat. D is correct because p and p1 are reference variables pointing to the same object in heap memory - so when p1.name = "Cat" mutates the object, both p and p1 see the change. The subsequent p = p1 is a no-op since they already point to the same object, giving "Cat" on the first…

Java Object-Oriented Approach

Question

Given the code fragment: Pet p = new Pet("Dog"); Pet p1 = p; p1.name = "Cat"; p = p1; System.out.println(p.name); p = null; System.out.println(p1.name); What is the result?

Options

  • ACat Dog
  • BA NullPointerException is thrown Cat Cat
  • CDog Dog
  • DCat Cat
  • ECat null

How the community answered

(25 responses)
  • B
    4% (1)
  • D
    92% (23)
  • E
    4% (1)

Explanation

D is correct because p and p1 are reference variables pointing to the same object in heap memory - so when p1.name = "Cat" mutates the object, both p and p1 see the change. The subsequent p = p1 is a no-op since they already point to the same object, giving "Cat" on the first print. Setting p = null only clears the p reference variable, leaving p1 intact and still pointing to the (now "Cat"-named) object, giving "Cat" on the second print.

Why distractors fail: A and C are wrong because "Dog" never appears - the mutation via p1.name overwrites it before any print occurs. B is wrong because the NullPointerException would only occur if you called p.name after p = null, but the second print uses p1, which is never nulled. E is wrong for the same reason - p1.name returns "Cat", not null, because p1 still holds a valid reference.

Memory tip: Think of reference variables as sticky notes pointing to a box - two sticky notes (p and p1) on the same box means changing the box's contents affects anyone reading from either note. Tearing off one sticky note (p = null) doesn't destroy the box; the other note (p1) still finds it.

Topics

#object references#reference aliasing#mutable state#null assignment

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice