Assertions in Java
In a previous blog, we learned about the types of Exceptions along with their examples. If you want to learn more about the types of exceptions visit Types of Exceptions in Java . In this blog, we will learn about the Assertions in Java. Let’s get started.
Assertions
Assertion in Java is a statement that guarantees the correctness of the assumptions which we have made in the code. We must use the assert keyword to achieve the assertion. When an assertion is executed it must be true. If it fails then JVM throws an error called AssertionError. Assertions are mainly used for testing purpose.
Syntax of Assertion
Assertion is done with the help of the assert keyword. assert statement can be used in two ways:
First Way:
Second Way
e.g.
Output
As we can see that the output is displayed without any error, this is because by default the assertions are disabled. After enabling the assertions we will get the following error:
Enabling Assertions
As we have been in the previous section, assertions are disabled by default. We have to run a command to enable it. The syntax to enable the assertions is as follows:
OR
Disabling Assertions
In order to disable the assertions we have to use the following statement:
OR
Why to use Assertion
- Unreachable code
- Documenting Assumptions
- Assertion is also used to make sure that the default switch case is not reached.
While executing the program the code which does not execute is called unreachable code. We use assertions to make unreachable code as unreachable.
e.g.
Many programmers use comments to document the assumptions.
e.g.
In the above example rather than using comments, we can use assert. Because as the program grows it is possible that the comments can get out of date and out of sync. In this case we will have to use assert statements, otherwise they will fail even for the valid condition.
e.g.
e.g.
In the above example there is no default value which means that one of these 12 cases will always get executed. But if suppose there is a situation where due to some reason none of the cases is executed then the assumption will be false. This assumption should be verified using an assertion to make sure that the default switch case is not reached.
e.g.
Where not to use Assertions
- We should not use Assertions on command line arguments.
- We should not use Assertions to replace error messages.
- We should not use Assertions to check arguments in the public methods.