Java Assertions

Any assumptions made in the programme can be tested to see if they are accurate using an assertion. The assert statement in Java is used to create an assertion. It is assumed to be true while the assertion is being executed. JVM throws an error called AssertionError if it fails. It is primarily employed during development for testing purposes. assert is used with boolean expressions

There are 2 different ways to write assert condition

  1. assert expression;
  2. assert expression1:expression2;

By default asserts are disabled. We need to enable them by giving the following commands:

java -ea solution  or  java -enable assertions solution

To disable assertions, 

java -da solution  or  java -disable assertions solution

solution is the name of the file

In the above code, our assumption was WRONG, as array length is > 1, so it gave an Error message

In the above code, our assumption was CORRECT, as the array length is > 1, so it didn’t give an Error message.

Advantages of Assertions  

Anywhere a programmer can check whether their presumptions are correct.

  1. To confirm that a code that appears to be unreachable actually is.
  2. To confirm the accuracy of any assumptions made in comments 
  3. In order to prevent reaching the default switch case
  4. To examine the Object’s condition

Where not to use Assertions?

  1. Command line arguments shouldn’t be used with assertions.
  2. It is not recommended to use assertions in place of error messages. Since they could have been supplied by the user, assertions shouldn’t be used to validate arguments in public methods. 
  3. To handle errors supplied by users, error handling should be used.

Special thanks to Shreyas Vishwakarma for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article