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
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)- A5% (1)
- B10% (2)
- C85% (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-voidtype;System.out.println()returnsvoid. - C - fails on two counts: (1) the condition
fuelLevel < 1is logically backwards - it asserts fuel should be low, not high; (2)System.exit(0)also returnsvoid, 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.