Difficulty: Easy
Correct Answer: In an assert statement, the expression after the colon ( : ) can be any Java expression.
Explanation:
Introduction / Context:
Java’s assert statement has two forms: assert booleanExpr;
and assert booleanExpr : detailExpr;
. The colon form supplies a “detail” value that will be included in the AssertionError if the boolean expression evaluates to false. Understanding what is allowed after the colon is key.
Given Data / Assumptions:
Concept / Approach:
The language specification permits any expression after the colon; there is no restriction that it be a String literal. However, best practice is to avoid side effects in either expression, because assertions may be disabled at runtime and side effects would then disappear.
Step-by-Step Solution:
Check A: Correct. detailExpr may be any expression; its value is attached to the AssertionError.Check B: Asserts are not a replacement for switch default logic; they are intended for debugging invariants, not production control flow.Check C: If detailExpr has no value (e.g., is a statement), the code would not compile; it must be an expression with a value.Check D: Catching AssertionError is discouraged; assertions signal programmer errors and should not be used for recoverable conditions.
Verification / Alternative check:
Experiment with assert x > 0 : x
and assert flag : computeMessage()
. Both compile if expressions are valid. Attempting to place a statement (e.g., assignment used purely for side effect) will compile only if it yields a value, but this is bad style.
Why Other Options Are Wrong:
They either misuse assertion semantics or suggest poor practices.
Common Pitfalls:
Putting side effects in detail expressions; relying on assertions for normal input validation of public APIs.
Final Answer:
In an assert statement, the expression after the colon ( : ) can be any Java expression.
Discussion & Comments