The assert statement

index
INTERMEDIATE

The assert statement is unusual in that it usually "doesn't do anything." Rather, it is a form of executable documentation.

There are two forms:

assert boolean_expression;
assert boolean_expression : expression;

Execution is as follows. The boolean_expression is evaluated, and if true, control just passes to the next statement. But if it is false, an AssertionError is thrown (see exceptions), which typically halts your program with an error message. If the second form is used, the expression is included in the error message.

Depending on your compiler settings, assert statements may be ignored. This is seldom a good idea. To ensure that assert statements are executed, use the compiler flag -enableassertions or its abbreviation -ea.

STYLE

The purpose of the assert statement is to state things that you believe will always be true at that point in the program. It should not be used to check for possible error conditions that you believe could happen; for that, you should throw an exception.

It is a good idea to get into the habit of putting in assert statements, as appropriate, when you write the code.

There is little point in using the second form (with expression) unless you have something additional to say. For example, if you believe (say, in a binary search method) that some array index i is always within the array bounds, you might say

assert i >= 0 && i < myArray.length : "Array index is " + i;

Finally, the idiom assert false; can be used to indicate that you believe that a certain section of code (for example, the default case of a switch statement) can never be reached. However, it is a syntax error to put this (or any other) statement in a location that the Java compiler knows cannot be reached, such as immediately following a return statement.