Java assertions: choose the single true statement about enabling scope and appropriate usage.

Difficulty: Easy

Correct Answer: Assertions can be enabled or disabled on a class-by-class basis.

Explanation:

Introduction / Context:Assertions are a development-time tool. This question differentiates what the VM can control at runtime, and what assertions are good for versus what they are not.

Given Data / Assumptions:

  • VM options include -ea and -da with package/class selectors.
  • Assertions throw AssertionError when enabled and the condition is false.
  • Public API argument validation should not rely on assertions (they may be disabled).

Concept / Approach:Evaluate each statement strictly against VM behavior and recommended usage.

Step-by-Step Solution:A: True. Enable/disable can target specific classes (e.g., -ea:com.example.Foo).B: False. Java does not use “conditional compilation” for assertions; the bytecode remains, and runtime flags control execution.C: False in general for public methods; use explicit checks and throw exceptions. Assertions may be disabled, making them unsuitable for validating public inputs.D: False. If an assertion fails, the runtime throws AssertionError; you do not “choose” an alternate return or exception in the assert statement itself.

Verification / Alternative check:Run a small program with -ea:MyClass and observe that only that class’s assertions fire.

Why Other Options Are Wrong:They mischaracterize Java’s compilation model or the intended purpose of assertions.

Common Pitfalls:Using assertions for user input checking; assuming they are optimized out by the compiler like C’s preprocessor.

Final Answer:Assertions can be enabled or disabled on a class-by-class basis.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion