xhtml
 

Assertions

Another thing you can do is to insert assertions. An assertion consists of the assert keyword, followed by a boolean expression which you expect to be true if the code is working up to that point. Optionally, you can follow that with a colon and a message or expression to be printed out if the assertion isn't true.

assert n < 10 : "n too big: " + n;

This is equivalent to saying "if debugging is on and the test is false, print the message and stop the program", except that the compiler supports assertions at no cost, so you can safely leave them in as long as you want. By default, assertions are switched off. While you are debugging, you switch them on by running the program with the "enable assertions" flag. This tutorial always runs programs with assertions enabled.

java -ea Program

Back