Updated April 5, 2023
Introduction to Java Assertion
In Java, Assertion is a statement that ensures or tests the correctness of the assumptions made in a program. It is done with the help of the assert statement. When the written assumption is executed, it is considered as true. If it is false, an assertion error will be thrown by the Java Virtual Machine.
The main reasons why Assertions are used are:
- To confirm whether an unreachable code is reachable.
- To check whether the assumptions available in the comments are correct or not.
- To confirm, the default case in the switch is not reached.
- After the invocation of a method.
- To check the state of an object.
Syntax
Below is the syntax of the Java Assertion statement.
assert expression;
assert expr1 : expr2;
Any of these syntaxes can be used based on the requirement.
How does Assertion work in Java?
As already mentioned, assert can be written in two forms.
- The syntax asserts expression; is used in order to test the expressions of Boolean form. If the particular expression is false, the program gets terminated by throwing an AssertionError. Unlike the normal exceptions, these errors are disabled during runtime.
- However, the syntax asserts expr1: expr2; it is used in cases where the program has some extra information that helps diagnose certain failures.
- Similar to the uncaught exceptions in Java, assertion errors are commonly labeled in stack trace along with the file as well as line number from which the exception is thrown.
Even though these are the main pros of Assertion, there are certain situations where Assertions should not be used. They are:
- Error message replacement.
- Argument checking in public methods
- Command-line arguments.
Syntax
java –ea programname
Or
java –enable assertions programname
Steps to use Eclipse Java Assertion
In Eclipse, it can be done using the below steps.
Step 1: Select Run Configurations.
Step 2: Go to the left panel and select Java Application, and Right-click on it.
Step 3: Select New configuration and type –ea on VM Arguments. Once it is done, click.
Similarly, assertions can be disabled using the syntax given below. Java –da programname
Examples to Implement Java Assertion
Now, let us see some sample programs for the assertion in order to get a clear idea of the same.
Example #1
Java program to check whether a particular value is higher than 20.
Code:
class AssertionExample{
public static void main( String args[] ){
int val = 14;
assert val>=20:" Value is not valid";
System.out.println("The given value is: "+ val);
}
}
Output:
- On executing the code, the message “The given value is 14” gets displayed.
- It can be clearly seen that assertion is not checked here since the value is greater than 20 is not checked.
- In order to enable assertion, -ea has to be set before compiling. For that, perform the steps mentioned in NOTE.
- If you again try to run the code, it can be clearly seen that an AssertionError has been thrown since the value is less than 20.
Example #2
Java program to check whether a particular user input value is higher than 20.
Code:
import java.util.Scanner;
class AssertionExample{
public static void main( String args[] ){
Scanner sc = new Scanner( System.in );
System.out.print("Enter a number to check assertion ");
//store the input value to the variable val
int val = sc.nextInt();
//assertion check whether the input value is greater than 20
assert val>=20:" Value is not valid";
System.out.println("The given value is: "+ val);
}
}
Output:
- The user will be asked to input a number on executing the code. In the below result, the number 13 is given as input. Since it is less than 20, an AssertionError has been thrown.
- At the same time, when a value which is greater than 20 is given, no errors are thrown, and the message gets displayed.
Example #3
Java program to check the number of days in a week.
Code:
class AssertionExample {
//main method
public static void main(String args[]) {
//declare a string days
String[] days = {" Monday " , " Holiday " , " Saturday " , " Tuesday " , " Wednesday " , " Sunday " , " Thursday " , " Friday " };
//set the assertion as 7
assert days.length==7 : "7 days are present in a week, Your input is wrong";
//print the line below
System.out.println("There are " + days.length + " days in a week");
}
}
Output:
- On executing the code, an assertion error is thrown as the number of days in a week is 7, and the string input given contains more than that.
- Let us remove Holiday from the input values and see what the output will be.
Yes. The line gets printed as the assertion value satisfies the input value.
Advantages of using Assertion in Java
The following are the main advantages of using Assertion.
- Efficient detection and correction of bugs.
- Boilerplate code will be removed and helps in creating a readable code.
- Execution time won’t be affected since it gets removed automatically during runtime.
- Quick bug detection and correction.
- Code optimization and refactoring is done with high confidence in order to function correctly.
In addition to the above points, below are the important points that have to be known while studying Assertions.
- An assertion in Java is introduced in the version JDK 1.4
- Assert is the keyword used in order to implement assertion.
- Enabling and disabling of assertion can be done at runtime with the help of corresponding syntaxes.
- Even though assertion compliments the exception, it does not replace the exception.
- It does not replace the unit testing even if it helps in the validation of conditions.
- Never use assertion for arguments or parameters validation of a method that is public.
Conclusion
Java Assertion is a statement that checks the trueness of a particular condition. It is commonly used in testing during software development. Moreover, they are used with certain Boolean expressions. In this article, several aspects such as syntax, working, pros, cons, and examples of Assertion is explained in detail.
Recommended Articles
This is a guide to Java Assertion. Here we discuss an introduction to Java Assertion, how does it work, steps to use, advantages and examples for better understanding. You can also go through our other related articles to learn more –