Java: How does the assert keyword work?
By default, an assert statement does nothing at all. However, if you launch your program with the VM option
-ea for short):
$ java -enableassertions com.example.Main
Then this statement
is equivalent to
if (!cond) throw new AssertionError();
assert i == 0; is equivalent to
if (i != 0) throw new AssertionError();
The Java Language Specification states the following:
JLS §14.1014.10. The
An assertion is an
assertstatement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to
false. If the assertion is disabled, execution of the assertion has no effect whatsoever.
Where “enabled or disabled” is controlled with the
-ea switch and “An error is reported” means that an
AssertionError is thrown.
Adding an error message
A lesser known feature of
assert is that you can append an error message. For example:
assert o != null : "o is null";
The message is passed to the
AssertionError constructor and is for instance printed along with the stacktrace.