An assertion is a statement that will be evauated during the execution of a program. It returns a boolean result. If the result is true, the code executes normally and no other action takes place. This confirms that the assumed statement is true. If the result is false, an AssertionError is thrown. The assertion condition is tested using the assert keyword. The assert keyword has the following two forms:
- assert assertCondition;
Here, assertCondition is an expression that evaluates to a boolean expression. - assert assertCondition : exp;
Here, an expression exp is passed to the AssertionError in case an error is thrown at runtime.
An assertion can be enabled or disabled for a class or a package during runtime as follows:
- -da ClassName or -da PackageName: This will disable the assertion for a class or a package respectively.
- -ea ClassName or -ea PackageName: This will enable the assertion for a class or a package respectively.
The following code illustrates how illustrations are used:
public class Test
{
public static void main(String[] args)
{
int x =1;
assert(x==1);
assert(x ==2) : testA();
assert(x++>1): new Test();
}
public static void testA()
{
System.out.println(“Inside the method testA”);
}
}
Responses to “What is an assertion?”