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 -enableassertions (or -ea for short):

$ java -ea com.example.Main

Then this statement

assert cond;

is equivalent to

if (!cond)
    throw new AssertionError();

For example, assert i == 0; is equivalent to

if (i != 0)
    throw new AssertionError();

The Java Language Specification states the following:

14.10. The assert Statement
An assertion is an assert statement 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. JLS §14.10

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.


Be the first to comment!