nerdexam
Oracle

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…

Java Object-Oriented Approach

Question

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 main(String[] args) { Person p = null; checkPerson(p); p = new Person("Mary"); checkPerson(p); System.out.println(p); } public static Person checkPerson(Person p) { if (p == null) { p = new Person("Joe"); }else{ p = null; } return p; } } What is the result?

Options

  • AJoeMarry
  • BJoeNull
  • CNullNull
  • DNullMary

How the community answered

(29 responses)
  • A
    3% (1)
  • B
    17% (5)
  • C
    7% (2)
  • D
    72% (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 checkPerson call changed main's p to Joe - it didn't.
  • B (JoeNull) assumes both calls mutated main's p - neither did.
  • C (NullNull) correctly identifies the first state but wrongly assumes the second call sets main's p to 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

#reference semantics#pass-by-value#method parameters#object scope

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice