Java Reference ยท Keywords and Statements
The assert statement
Reference for the Java assert statement: syntax with a message, enabling with -ea, AssertionError, when to use assertions and when to validate instead.
assert checks a condition that you believe is always true at that point in the program. If the condition is false, the JVM throws an AssertionError. Assertions document assumptions and catch programming errors during development and testing.
Assertions are disabled by default. The JVM skips them completely unless it is started with -ea (or -enableassertions), so the condition must have no side effects and must never be used to validate user input or arguments of public methods.
assert index >= 0 : "index must not be negative: " + index;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
assert condition; assert condition : detailExpression;
| Part | Description |
|---|---|
condition |
A boolean expression. If it is false, an AssertionError is thrown. |
detailExpression |
Optional, any non-void value. Converted to a string and used as the message; if it is a Throwable it also becomes the cause. It is evaluated only when the condition fails. |
Command-line switches: java -ea enables all assertions, -ea:com.example... enables them for a package, -da disables, -esa enables them in system classes.
Usage notes
- No side effects. Code such as
assert list.remove(x);changes behavior depending on the flag. Compute first, assert the result. - Not for argument checking. Public methods should validate with
IllegalArgumentException,Objects.requireNonNull()and friends, which always run. Useassertfor internal invariants, private helpers and "cannot happen" branches. AssertionErroris anError, not anException, so a normalcatch (Exception e)does not catch it. Do not catch it to recover.- Cost when disabled is a single flag check at class initialization; the condition is not evaluated.
- Unit tests should use the assertions of a test framework (JUnit's
assertEquals), which always run, rather than theassertkeyword. - Typical uses: loop invariants, post-conditions of private methods,
defaultbranches that should be unreachable (assert false : "unreachable"; or throwAssertionErrordirectly, which works with assertions off). - Keyword history:
asserthas been reserved since Java 1.4. Older code could use it as an identifier. - Enabling in tools: Maven Surefire and Gradle enable assertions by default for tests.