Assertion keyword in Java

An assert is a keyword in Java which enables us to test our assumptions about our program.

Assert will throw exception, If its expression evaluates to false and do nothing if it’s true.


Syntax :
assert Expression1 ;

Where,
Expression1 is a boolean expression.

When the system runs the assertion, it evaluates Expression1 and if it is false then throws an AssertionError with no detail message.

The second form of the assertion statement is:

assert Expression1 : Expression2 ;

Where,
Expression1 is a boolean expression.

Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

Expression2 is used as a detailed error message if it exists.


Consider the below example


If we are calculating the total salary of all employees in a company and we need to assure that total salary of all employees will not exceed 10 lacs.

Then we can use assert as below

assert totalSalary <= 1000000 : “Total salary should not be greater than 10 lacs”;

Each assertion contains a boolean expression that we assume will be true when the assertion executes. If it is not true, the system will throw an error.

By verifying that the boolean expression is indeed true, the assertion confirms our assumptions about the behavior of our program, increasing our confidence that the program is free of errors.

How to enable the assertion?

  1. public class Employee {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.                                                   // Assume below method call gets total salary
  6.    
  7.                                       float totalSalary = getTotalSalary();
  8.                                      
  9.                                       assert totalSalary <= 1000000:”Total Salary should not be more than 10 lacs”;
  10.  
  11.                                                        // stops if totalSalary  is greater than 10 lacs
  12.  
  13.                                       System.out.println("Success");
  14.  
  15.                                     }
  16. }
public class Employee {

    public static void main(String[] args) {

                                                  // Assume below method call gets total salary
    
                                      float totalSalary = getTotalSalary();
                                      
                                      assert totalSalary <= 1000000:”Total Salary should not be more than 10 lacs”; 

                                                       // stops if totalSalary  is greater than 10 lacs
  
                                      System.out.println("Success");
 
                                    }
}


Assertion in java is disabled by default and the same can be enabled as below

java –ea class name

java –ea Employee

where,
–ea is enableassertion
Employee is the class name.

Use case 1 :

Java –ea Employee

totalSalary is 7 lacs then if we run the above program by enabling assertion

This will print the output as “success”.

Use case 2:

Java –ea Employee

totalSalary is 11 lacs then if we run the above program by enabling assertion

This will throw an assertion error as below

Exception in thread "main" java.lang.AssertionError : Total Salary should not be more than 10 lacs

When to use assertion?


Assertions should be used to check something that should never happen in our application and we can use it whenever we want to verify our assumptions with the pre-conditions in our code.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on