1Z0-809 · Question #208
Given: `` public class Product { public double applyDiscount(double price) { assert (price > 0); // line n1 return price * 0.50; } public static void main(String[] args) { Product p = new Product()…
The correct answer is C. New Price: 0.0. Option C is correct because Java assertions are disabled by default at runtime - you must explicitly enable them with the -ea (enable assertions) JVM flag. Since the command is java Product 0 without -ea, the assert statement on line n1 is completely ignored, price remains 0.0…
Question
public class Product {
public double applyDiscount(double price) {
assert (price > 0); // line n1
return price * 0.50;
}
public static void main(String[] args) {
Product p = new Product();
double newPrice =
p.applyDiscount(Double.parseDouble(args[0]));
System.out.println("New Price: " + newPrice);
}
}
and the command: java Product 0
What is the result?Options
- AAn AssertionError is thrown.
- BA compilation error occurs at line n1.
- CNew Price: 0.0
- DA NumberFormatException is thrown at run time.
How the community answered
(19 responses)- A11% (2)
- B5% (1)
- C79% (15)
- D5% (1)
Explanation
Option C is correct because Java assertions are disabled by default at runtime - you must explicitly enable them with the -ea (enable assertions) JVM flag. Since the command is java Product 0 without -ea, the assert statement on line n1 is completely ignored, price remains 0.0, and the calculation 0.0 * 0.50 yields 0.0, producing New Price: 0.0.
Why the distractors are wrong:
- A is wrong because even though
0 > 0isfalse, theAssertionErroris never triggered - assertions are off unless you runjava -ea Product 0. - B is wrong because
assertis valid Java syntax (introduced in Java 1.4); there is no compilation error. - D is wrong because
Double.parseDouble("0")is perfectly valid and returns0.0; aNumberFormatExceptionwould only occur for a non-numeric string like"abc".
Memory tip: Think of assertions as a "practice mode" switch - they ship off by default so production performance isn't affected, and you flip them on with -ea only when debugging or testing. On the exam, whenever you see assert without -ea in the command, treat that line as if it doesn't exist.
Community Discussion
No community discussion yet for this question.