Java Assertion and AssertionError

Assert Statement in Java

1. What is Java Assertion?

Java Assertion is a pre-condition which checks for the program correctness at a specific code location. Coder will place these assertions at needed location of the program to check it meets certain requisites to go on with the rest of the code flow. In java, a condition which follows the assert keyword evaluates to true or false.

2. Raising Assertion & AssertionError Class

Have a look at the below picture:

Assert Statement in Java
Assert Statement in Java

You can see assertion tests a condition. Java will throw AssertionError when the condition returns false, and execution goes smoothly when condition returns true. You can read assertion as “Make Sure with a condition”. For Example:

Here, you read this statement as “Make sure DbConnection is not Null”. What happens if it is null? The JVM reports an Assertion Error. AssertionError is a Java SDK Class, which is derived from the Error class. So, the raised assertion falls under Unchecked Exception. We can raise assertion in two flavors:

  1. Raise AssertionError which shown in the first box of the picture
  2. Raise AssertionError with a message and you can see that in the second part of the picture.

3. JVM parameter -ea (Enable Assertions)

By default, Java disables assertion as it is not suitable for end-user box. To enable, you must pass -ea switch to java command. Here, ea stands for Enable Assertion. When we launch the program with this switch, it will raise the Assertion Errors when conditional check points not satisfied. This will help the programmers to correct the error when they code and avoid such errors pushed to test team or production.

4. Example for Java Assertion

Now we will see an example of how to raise AssertionError from the java code. Have a look at the below piece of code:

Java Assertion Example
Java Assertion Example

The above code calculated incentive for an employee. Even though the Incentive is flat 25%, the code checks Employee worked at-least one day. This is to avoid further error in the code flow. In our case, we use the Java’s assert keyword to make sure employee worked at-least one day. Otherwise, the code will raise an AssertionError.

Recall, AssertionError is an unchecked exception as it is extending from the Error class. So, raising assertion will inform the JVM to halt the program execution. You can watch this article as a video below.

Video: Java Assertion Explained

5. Code Reference

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.