nerdexam
Oracle

1Z0-809 · Question #200

Given: class Engine { double fuelLevel; Engine(int fuelLevel) { this.fuelLevel = fuelLevel; } public void start() { // line n1 System.out.println("Started"); } public void stop() {…

The correct answer is C. assert fuelLevel < 1: System.exit(0). Warning: The stated correct answer (C) appears to be incorrect. Option D is the right answer. Here's why: Why D is correct: assert fuelLevel > 0: "Impossible fuel"; uses valid Java assert syntax - if fuelLevel is not greater than zero, Java throws an AssertionError (with the…

Question

Given: class Engine { double fuelLevel; Engine(int fuelLevel) { this.fuelLevel = fuelLevel; } public void start() { // line n1 System.out.println("Started"); } public void stop() { System.out.println("Stopped"); } } Your design requires that: - fuelLevel of Engine must be greater than zero when the start() method is invoked. - The code must terminate if fuelLevel of Engine is less than or equal to zero. Which code fragment should be added at line n1 to express this invariant condition?

Options

  • Aassert fuelLevel > 0; "Terminating...";
  • Bassert (fuelLevel > 0) : System.out.println("Impossible fuel");
  • Cassert fuelLevel < 1: System.exit(0);
  • Dassert fuelLevel > 0: "Impossible fuel";

How the community answered

(20 responses)
  • A
    5% (1)
  • B
    10% (2)
  • C
    85% (17)

Explanation

Warning: The stated correct answer (C) appears to be incorrect. Option D is the right answer. Here's why:

Why D is correct: assert fuelLevel > 0: "Impossible fuel"; uses valid Java assert syntax - if fuelLevel is not greater than zero, Java throws an AssertionError (with the string message as detail), which terminates execution. This precisely matches the invariant: pass when fuel > 0, terminate otherwise.

Why each other option is wrong:

  • A - assert fuelLevel > 0; "Terminating..."; is a compile error. After the semicolon ends the assert statement, "Terminating..." is a bare string literal, which is not a valid Java statement.
  • B - assert (fuelLevel > 0) : System.out.println(...) is a compile error. The expression after the colon must have a non-void type; System.out.println() returns void.
  • C - fails on two counts: (1) the condition fuelLevel < 1 is logically backwards - it asserts fuel should be low, not high; (2) System.exit(0) also returns void, which is illegal as the assert detail expression, making this another compile error.

Memory tip: Java assert syntax is assert <condition> : <non-void-expression>; - read it as "assert this must be true, otherwise blame [message]." The condition should be your positive invariant (> 0, not < 1), and the message must produce an actual value (a String is the most common choice).

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice