It throws an error 'AssertionError' if the condition is not fulfilled (the condition returns false). Note that you should never try to catch this error.
The assertion code 'evaporates' when the program is deployed, leaving behind no overhead or debugging code to truck down or remove.
// Throws an AssertionError if the condition is false
assert(num >= 0);
// Same than the previous example with a custom message
assert(num >= 0) : "My custom message, value of num= "+num;
Note that in assert() : [expression] the expression after the colon (:) should return a value (it can not be a void).Enable assert
Assertions are disabled by default. It means that you can use them in your code as a keyword (since java 1.4) but they will be ignored during runtime. If you want to enable assertions during runtime, you have to specify it.
// Enable assertions for a class:
java -ea MyClass
// or:
java -enableassertions MyClass
// Enable assertions for a package:
java -ea com.mypackage...
You can also use the options '-de' or 'disableassertions' in order to disable the assertions for specified packages or classes, if the assertions are enabled.
// Enable assertions for all packages except one:
javac -ea -da:com.mypackage...
// or:
java -ea -disableassertions:com.mypackage...
assert as identifier
Note that you can use 'assert' as an identifier (variable or method's name) with the versions of Java preceding 1.4. In this case, you have to compile with 1.3 or older version:
java -source 1.3 myClassThis will compile but it will still display a warning: "warning: as of release 1.4, 'assert' is a keyword, and may not be used as an identifier".