Assertions in Java
An Introduction |
Prof. David Bernstein
|
Computer Science Department |
bernstdh@jmu.edu |
if
statement (e.g., that throws
an exception) if the assumption doesn't holdassert boolean_expression;
assert boolean_expression : expression;
-enableassertions
(or -ea
)
switch to enable and/or the
-disableassertions
(or -da
)
switch to disable
This fragment assumes i
is non-negative.
One Approach:
Another Approach:
The Original Code Ignoring the Invariant:
Alternative Code Ignoring the Invariant:
Taking Advantage of the Invariant Using an Assertion:
This fragment assumes that there are only four suits.
Using an assertion