Java

Why assertions are used ? How they are useful in software testing in Java ?2 min read

In this article we will learn what are assertions. How to create and use assertions in Java programs and how to enable and disable assertions while running a Java program.

Assertions in Java

Definition: An assertion is a condition that should be true during the program execution. They are generally used to detect errors (testing) during development of software. They have no use after the code is released to the users. They encourage defensive programming.




Creating and Using Assertions:

Assertions can be created using the assert keyword. The general form of using assert keyword is as follows:

When the given condition becomes false, AssertionError is thrown by the Java run-time. The second form of assert is as follows:

In the above syntax, expr can be any non-void value which will be passed on to the constructor of AssertionError and will be displayed as an error message.

Enabling and Disabling Assertions:

For enabling them we have to use the following syntax while executing a Java program:

Where -ea denotes enable assertion and similarly for disabling them we can use the following syntax:

Where -da denotes disable assertion.

For enabling or disabling assertion in a package we can use the following syntax:

Sample Program:

Let’s consider a Java program where the numbers entered by the user must not be negative values. To implement this we can use assert keyword as follows:

If the n value is given as -9, then output of the above program is:

As the above error message does not give much information we can use second form of assert as shown in the below program:

Now the output of the above program for -9 as n value is:

Use the following links for more information on assertions:

Consider giving us a comment help us make our articles better.

Leave a Comment