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
- assert expression;
- 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.
- To confirm that a code that appears to be unreachable actually is.
- To confirm the accuracy of any assumptions made in comments
- In order to prevent reaching the default switch case
- To examine the Object’s condition
Where not to use Assertions?
- Command line arguments shouldn’t be used with assertions.
- 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.
- 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