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:
1 2 3 |
assert condition; |
When the given condition becomes false, AssertionError is thrown by the Java run-time. The second form of assert is as follows:
1 2 3 |
assert condition : expr; |
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:
1 2 3 |
java -ea ClassName |
Where -ea denotes enable assertion and similarly for disabling them we can use the following syntax:
1 2 3 |
java -da ClassName |
Where -da denotes disable assertion.
For enabling or disabling assertion in a package we can use the following syntax:
1 2 3 |
java [-ea | -da] [:package-name… | :ClassName] |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Scanner; class AssertionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter n: "); int n = input.nextInt(); assert n>0; System.out.println("n = " + n); } } |
If the n value is given as -9, then output of the above program is:
1 2 3 4 |
Exception in thread “main” java.lang.AssertionError at AssertionDemo.main(AssertionDemo.java:9) |
As the above error message does not give much information we can use second form of assert as shown in the below program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Scanner; class AssertionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter n: "); int n = input.nextInt(); assert n>0 : "n cannot be negative"; System.out.println("n = " + n); } } |
Now the output of the above program for -9 as n value is:
1 2 3 4 5 6 |
Exception in thread “main” java.lang.AssertionError: n cannot be negative at AssertionDemo.main(AssertionDemo.java:9) |
Use the following links for more information on assertions:
Consider giving us a comment help us make our articles better.