By default, assertions are not evaluated. It is possible to turn assertion evaluation on and off for packages,
classes, and entire class loaders, as you will soon see. When assertions are turned off, the assertions are not
evaluated at all. This means that you must be careful about side effects that affect non-assertion code. For
example, the following code is very dangerous:
assert ++i < max;
When assertions are being evaluated, the value of i will be incremented to the next value. But when someone
turns off assertions the entire expression will logically vanish from the code leaving i perpetually unchanged.
Don't ever do anything like this. Split it up:
i++;
assert i < max;
12.8.1. The assert Statement
The syntax for an assertion is:
assert eval-expr [: detail-expr];
where eval-expr is either a boolean or Boolean expression and detail-expr is an optional
expression that will be passed to the AssertionError constructor to help describe the problem. The detail
expression is optional; if present, it provides information to a person who looks at the statement or thrown
exception. If the detail is a Throwable it will become the cause of the AssertionError; that is, it will
be the value returned by the error's getCause method. Otherwise, the detail will be converted to a string and
become the detail message for the error.
When an assert is encountered in the code, the first expression is evaluated. If the resulting value is true,
the assertion passes. If it is false, the assertion fails, and an AssertionError will be constructed and
thrown.
12.9. When to Use Assertions
Assertions are typically used to make sure those things that "can't happen" are noticed if they do happen. This
is why a failed assertion throws a kind of Error instead of an Exception. A failed assertion means that
the current state is basically insane.
You should not use assertions to test for things that you know will actually happen sometimes
(IOException) or for which other means are common (IllegalArgumentException,
NullPointerException, ...). You want to deal with these problems whether or not assertions are being
evaluated. Assertions are for testing for things that should never happenin a properly functioning program no
assertion should ever fail. The next few sections show some good examples of when to use assertions.