In this tutorial, we will learn about the Java assertions with the help of examples.
An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program.
Java has a built-in package for Logging frameworks i.e,java.util.logging
.
assert condition;
Or
assert condition : expression
For using Assretions, you have to enable assertions as by default they are disabled and egnored at run-time. It is very easy to enable Assertions.
To enable assertions we use :
java -ea //This enables assertion for all classes
Or
java -ea:arguments //This enables assertion for given classes
Or
java -enableassertions:arguments
Example :
java -ea Main //enables in all classes of our Main program
Or
java -ea:CityClass Main //This enables assertion in only the CityClass in the Main program
When assertions are enabled and the condition is true, the program executes normally. But if the condition evaluates to false while assertions are enabled, JVM throws an AssertionError, and the program stops immediately.
To disable assertions we use :
java -da:arguments //This enables assertion for given classes
Or
java -disableassertions arguments