Skip to main content
Assertion Mechanism
- Assertions give you a way to test your assumptions during development and debugging.
- Assertions are typically enabled during testing but disabled during deployment.
- You can use assert as a keyword (as of version 1.4) or an
identifier, but not both together. To compile older code that uses
assert as an identifier (for example, a method name), use the -source
1.3 command-line flag to javac.
- Assertions are disabled at runtime by default. To enable them, use a command-line flag -ea or -enableassertions.
- Selectively disable assertions by using the -da or -disableassertions flag.
- If you enable or disable assertions using the flag without any
arguments, you're enabling or disabling assertions in general. You can
combine enabling and disabling switches to have assertions enabled for
some classes and/or packages, but not others.
- You can enable and disable assertions on a class-by-class basis, using the following syntax: java -ea -da:MyClass TestClass
- You can enable and disable assertions on a package-by-package basis,
and any package you specify also includes any subpackages (packages
further down the directory hierarchy).
- Do not use assertions to validate arguments to public methods.
- Do not use assert expressions that cause side effects. Assertions
aren't guaranteed to always run, and you don't want behavior that
changes depending on whether assertions are enabled.
- Do use assertions—even in public methods—to validate that a
particular code block will never be reached. You can use assert false;
for code that should never be reached, so that an assertion error is
thrown immediately if the assert statement is executed.