nerdexam
Oracle

1Z0-819 · Question #25

Given: public class Person { private String name = "Joe Bloggs"; public Person(String name) { this.name = name; } public String toString() { return name; } } and public class Tester { public static…

The correct answer is B. Joe Bloggs. There's actually an error in the provided answer key - option C is the correct answer, not B. Person defines an explicit constructor Person(String name), which means Java does not auto-generate a no-arg constructor. Line 1 calls new Person() with no arguments, so the compiler…

Java Object-Oriented Approach

Question

Given: public class Person { private String name = "Joe Bloggs"; public Person(String name) { this.name = name; } public String toString() { return name; } } and public class Tester { public static void main(String[] args) { Person p = new Person(); // line 1 System.out.println(p); } } What is the result?

Options

  • Anull
  • BJoe Bloggs
  • CThe compilation fails due to an er or in line 1.
  • Dp1

How the community answered

(48 responses)
  • A
    6% (3)
  • B
    79% (38)
  • C
    13% (6)
  • D
    2% (1)

Explanation

There's actually an error in the provided answer key - option C is the correct answer, not B.

Person defines an explicit constructor Person(String name), which means Java does not auto-generate a no-arg constructor. Line 1 calls new Person() with no arguments, so the compiler finds no matching constructor and fails with a compilation error. Option B ("Joe Bloggs") would only be reachable if the code actually compiled and ran - the field initializer name = "Joe Bloggs" is immediately overwritten by any Person(String name) call anyway, so B could never be printed via a no-arg path. Option A ("null") is wrong for the same reason - execution never begins. Option D ("p1") is a nonsensical distractor; p is the variable name, not p1, and toString() returns name, not the variable name regardless.

Memory tip: In Java, the free no-arg constructor disappears the moment you write any explicit constructor. Think of it as: "define one, you own them all" - if you want both, you must write both.

Topics

#Constructors#Object instantiation#Instance variables#toString

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice