Java assertions: pick the three true statements about when to enable, and how selectively to enable, assertion checking.

Difficulty: Easy

Correct Answer: 2, 3 and 5

Explanation:


Introduction / Context:
This question tests best practices and VM capabilities for assertions. Assertions are intended primarily for development and testing, not for normal production error handling or user input validation.


Given Data / Assumptions:

  • (1) “Assertion checking is typically enabled when a program is deployed.”
  • (2) “It is never appropriate to write code to handle failure of an assert statement.”
  • (3) “Assertion checking is typically enabled during program development and testing.”
  • (4) “Assertion checking can be selectively enabled/disabled on a per-package basis, but not per-class.”
  • (5) “Assertion checking can be selectively enabled/disabled on both a per-package basis and a per-class basis.”


Concept / Approach:
Assertions are primarily for detecting programmer errors and invariant violations in development. The VM supports enabling/disabling at multiple granularities via -ea/-da options, including package and class specificity.


Step-by-Step Solution:
(1) False: production deployments typically run with assertions disabled for performance and to avoid exposing internal checks to users.(2) True: you should not write recovery code for AssertionError; it indicates a bug. Do not catch it in normal flow.(3) True: enabling during development/testing helps surface latent defects early.(4) False: you can target individual classes as well as packages.(5) True: VM flags allow both per-package and per-class control.


Verification / Alternative check:
Use -ea:com.example... -da:com.example.Foo to see package enabled, class disabled. This demonstrates both per-package and per-class control.


Why Other Options Are Wrong:
Options that include statements (1) or (4) are invalid because those statements are false.


Common Pitfalls:
Treating assertions like user input checks; attempting to catch AssertionError in production code; assuming global on/off only.


Final Answer:
2, 3 and 5

Discussion & Comments

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