What are assertions in Java Programming

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:
assert condition;
When the given condition becomes falseAssertionError is thrown by the Java run-time. The second form of assert is as follows:
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:
java -ea ClassName
Where -ea denotes enable assertion and similarly for disabling them we can use the following syntax:
java -da ClassName
Where -da denotes disable assertion.
For enabling or disabling assertion in a package we can use the following syntax:
java [-ea | -da] [:package-name… | :ClassName]

Example 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:
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:

Now the output of the above program for -9 as n value is:
Exception in thread “main” java.lang.AssertionError:
n cannot be negative
at AssertionDemo.main(AssertionDemo.java:9)

Take your time to comment on this article


EmoticonEmoticon