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:

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:
1 |
assert (DbConnection != null) |
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:
- Raise AssertionError which shown in the first box of the picture
- 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:

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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class MainEntry { public static void main(String[] args) { //Sample 01: Variable & Initialization int Salary = 20000; int NumDaysPresent = 0; double Incentive; //Sample 02: Calculate Incentive assert (NumDaysPresent > 0) : "Employee should worked atleast 1 day in a month!!"; Incentive = (Salary * 0.25 * NumDaysPresent) / 28; System.out.println("Incentive Amount is: " + Math.round(Incentive) ); } } |
Categories: Java
Tags: assert keyword, AssertionError, Enable Assertion, Java -ea switch