1Z0-819 · Question #32
Given: public class Person { private String name; public Person(String name) { this.name = name; } public String toString() { return name; } } and public class Tester { public static void…
The correct answer is D. NullMary. Option D is correct because Java is pass-by-value: when p is passed to checkPerson, the method receives a copy of the reference, so reassigning the parameter inside the method never changes what p points to back in main. After the first call (p = null), checkPerson creates…
Question
Options
- AJoeMarry
- BJoeNull
- CNullNull
- DNullMary
How the community answered
(29 responses)- A3% (1)
- B17% (5)
- C7% (2)
- D72% (21)
Explanation
Option D is correct because Java is pass-by-value: when p is passed to checkPerson, the method receives a copy of the reference, so reassigning the parameter inside the method never changes what p points to back in main. After the first call (p = null), checkPerson creates "Joe" internally and the return value is ignored - p in main remains null. After p = new Person("Mary"), the second call sets the local copy to null, but again the return value is ignored, so p in main still points to "Mary" when println runs - producing the output Mary.
Why the distractors fail:
- A (JoeMarry) assumes the first
checkPersoncall changedmain'spto Joe - it didn't. - B (JoeNull) assumes both calls mutated
main'sp- neither did. - C (NullNull) correctly identifies the first state but wrongly assumes the second call sets
main'spto null.
Memory tip: Think of a reference variable as a house address on a sticky note. Passing it to a method gives the method its own sticky note with the same address - the method can scribble on its note all it wants, but your original note doesn't change.
Topics
Community Discussion
No community discussion yet for this question.