Home / Java Programming / Assertions :: Discussion

Discussion :: Assertions

  1. Which statement is true?

  2. A.
    Assertions can be enabled or disabled on a class-by-class basis.
    B.
    Conditional compilation is used to allow tested classes to run at full speed.
    C.
    Assertions are appropriate for checking the validity of arguments in a method.
    D.
    The programmer can choose to execute a return statement or to throw an exception if an assertion fails.

    View Answer

    Workspace

    Answer : Option A

    Explanation :

    Option A is correct. The assertion status can be set for a named top-level class and any nested classes contained therein. This setting takes precedence over the class loader's default assertion status, and over any applicable per-package default. If the named class is not a top-level class, the change of status will have no effect on the actual assertion status of any class.

    Option B is wrong. Is there such a thing as conditional compilation in Java?

    Option C is wrong. For private methods - yes. But do not use assertions to check the parameters of a public method. An assert is inappropriate in public methods because the method guarantees that it will always enforce the argument checks. A public method must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError.

    Option D is wrong. Because you're never supposed to handle an assertion failure. That means don't catch it with a catch clause and attempt to recover.


Be The First To Comment