assert Expression1 : Expression2;
- Expression1 is asserted to be true; otherwise
AssertionError(that shouldn’t be handled) is thrown - Expression2 allows to produce some additional information
- Expression2 MUST result in a value – it generates a String message
- allow testing during the development and debugging
- are disabled at runtime by default
- can be enabled using
-eaor-enableassertionsflags and selectively disabled using-daor-disableassertionsflags, e.g:java -ea -da:MyClass NotMyClass– enable in general but disable for MyClassjava -ea -da:net.dobrzanski.util... MyClass– enable in general but disable for all classes fromnet.dobrzanski.utilpackage and any of its subpackagesjava -ea -dsa MyClass, which is shorter version ofjava -enableassertions -disablesystemassertions MyClass– enable in general but disable in system classes
- DO NOT USE to validate arguments to public methods
- DO NOT USE to validate command line arguments
- USE to validate arguments to private methods
- USE to validate that particular code block will never be reached (use
assert false;in that case) assertcan be used as a key word (as of Java 1.4) or as an identifier, but never both at the same time
Shorter version:
private void doSth() {
...
assert (a < b);
// in there, a is lower than b
...
}
Longer version:
private void doSth() {
...
assert (a < b) : "a=" + a + ", b=" + b;
// in there, a is lower than b
...
}