nerdexam
Oracle

1Z0-819 · Question #146

Given: public class Price { private final double value; public Price(String value) { this(Double.parseDouble(value)); } public Price(double value) { this.value = value; } public Price () { public…

The correct answer is D. 1.99-0.0-2.99. Note: The code as written has a structural defect - the no-arg Price() constructor is never closed, making it malformed. The intended code almost certainly has public Price() {} as an empty constructor body, and value should not be final (a final field not initialized in a…

Java Object-Oriented Approach

Question

Given: public class Price { private final double value; public Price(String value) { this(Double.parseDouble(value)); } public Price(double value) { this.value = value; } public Price () { public double getValue() { return value; } public static void main(String[] args) { Price p1 = new Price("1.99"); Price p2 = new Price(); Price p3 = new Price(2.99); System.out.println(p1.getValue()+"-"+p2.getValue()+"-"+p3.getValue()); } } What is the result?

Options

  • AThe compilation fails.
  • B1.99-2.99-
  • C1.99-2.99-0.0
  • D1.99-0.0-2.99

How the community answered

(53 responses)
  • A
    9% (5)
  • B
    4% (2)
  • C
    15% (8)
  • D
    72% (38)

Explanation

Note: The code as written has a structural defect - the no-arg Price() constructor is never closed, making it malformed. The intended code almost certainly has public Price() {} as an empty constructor body, and value should not be final (a final field not initialized in a constructor causes a compile error). Assuming those are typos, D is correct because:

p1 = new Price("1.99") chains via this(Double.parseDouble("1.99")) to Price(double), setting value = 1.99. p2 = new Price() uses the empty no-arg constructor, leaving value at Java's default for double: 0.0. p3 = new Price(2.99) directly sets value = 2.99. The println concatenates them in declaration order - p1, p2, p3 - producing 1.99-0.0-2.99.

Why the distractors fail:

  • A would be correct as written (due to final + uninitialized field), but the question intends a compiling version.
  • B (1.99-2.99-) is nonsensical - there's no scenario that produces a trailing dash with a missing third value.
  • C (1.99-2.99-0.0) is a trap for students who assume the no-arg constructor somehow calls Price(2.99), swapping p2 and p3's values.

Memory tip: When you see constructor chaining with this(...), trace the delegation chain first - each constructor only assigns value when it reaches the one with this.value = .... Any constructor that doesn't assign value leaves it at its type's default (0.0 for double).

Topics

#Constructors#Constructor chaining#Final fields#Method overloading

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice