Java Reference
In-Depth Information
Note that we translated only one of the three comments into an assertion check.
Not all assertion comments lend themselves to becoming assertion checks. For exam-
ple, there is no simple way to convert the other two comments into Boolean expres-
sions. Doing so would not be impossible, but you would need to use code that would
itself be more complicated than what you would be checking.
Assertion Checking
An assertion check is a Java statement consisting of the keyword assert followed by a Bool-
ean expression and a semicolon. If assertion checking is turned on and the Boolean expression
in the assertion check evaluates to false when the assertion check is executed, the program
will end and output a suitable error message. If assertion checking is not turned on, the asser-
tion check is treated as a comment.
SYNTAX
assertion
check
assert Boolean_Expression ;
EXAMPLE
assert (n == 0) && (sum == 0);
You can turn assertion checking on and off. When debugging code, you can turn
assertion checking on so that a failed assertion will produce an error message. Once
your code is debugged, you can turn assertion checking off and your code will run
more efficiently.
A program or other class containing assertions is compiled in the usual way. After
all classes used in a program are compiled, you can run the program with assertion
checking either turned on or turned off.
If you compile your classes using a one-line command, you would compile a class
with assertion in the usual way:
javac YourProgram.java
You can then run your program with assertion checking turned on or off. The normal
way of running a program has assertion checking turned off. To run your program
with assertion checking turned on, use the following command:
java -enableassertions YourProgram
If you are using an IDE, check the documentation for your IDE to see how to han-
dle assertion checking. If you do not find an entry for “assertion checking,” which is
likely, check to see how you set run options. (With TextPad, you can set things up for
assertion checking as follows: On the Configure menu, choose Preferences, and then
Search WWH ::




Custom Search