dsa

Java Assertions

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.

Syntax :

assert condition;
Or

assert condition : expression

Enabling Assertions

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.

Disabling Assertions

To disable assertions we use :


java -da:arguments   //This enables assertion for given classes
Or

java -disableassertions arguments

Why to use Assertions?

  • To check that an unreachable looking code is actually unreachable.
  • To check that assumptions written in comments are right.
  • Quick and efficient for detecting and correcting bugs.

When to use Assertions?

  • Conditional Cases
  • Unreachable Codes
  • In the arguments to private methods. Private arguments are provided by developer’s code only and developer may want to check his/her assumptions about arguments.

When not to use Assertions?

  • Should not be used to replace error messages.
  • Argument checking in public methods.