What is Assertion in Java?
The assertion in Java is used to ensure the correctness of any program’s assumptions as the assertion is assumed to be true when it is executed. The Java Virtual Machine throws an error named AssertionError if the assertion is false. The assertion in Java has found its application mainly for testing purposes. Boolean expressions are used along with assertion statements. An assertion is a statement, and the ‘asset’ keyword is used to carry out an assertion in Java.
Check out our free courses to get an edge over the competition
Syntax
The following are two ways in which assertion is carried out in Java:
1. assert expression;
2. assert expression1: expression2;
Explore Our Software Development Free Courses
How to Use Assertion in Java?
Assertions are disabled in Java by default. The following command is used to enable them:
java -ea Test
(or)
java -enableassertions Test
where Test is the name of the Java file.
Here is an example to demonstrate the syntax of assertion:
public class Test
{
public static void main(String[] args)
{
int value = 13;
assert value <= 12 : “Not Teen”;
System.out.println(“The age of teenager is ” + value);
}
}
Check out upGrad’s Java Bootcamp
Output
Here is an example for the generation of an assertion error by the Java Virtual Machine –
class Test
{
public static void main( String args[] )
{
int weight = 30;
assert weight >= 20 : ” Overweight”;
System.out.println(“Weight is “+value);
}
}
Output
After enabling assertions,
Output
Exception in thread “main” java.lang.AssertionError: Overweight
This is what it looks like:
Explore our Popular Software Engineering Courses
Why Use Assertions?
The assertion in Java is used to:
- Check if the assumptions made by the programmer are correct or not.
- Make sure that if the code looks unreachable, it is unreachable.
- Confirm that assumptions written in the comments are correct, for example:
Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)
if ((y & 1) == 1)
{ }
else // y must be even
{ assert (y % 2 == 0); }
- ensure default switch case is not being reached
- check the state of the object
The assertion in Java is used at the beginning of the method and after the method invocation.
Where to use Assertions?
The assertion in Java is used in conditional cases and when conditions are at the beginning of any method. Also, in the case of arguments to private methods. The developer’s code provides private arguments and when the programmer needs to check his/her assumptions regarding the arguments.
Here are some situations in which the use of assertions should be avoided:
- As per the specifications given by Sun Microsystems, the assertion should not be used while checking arguments in the public methods because that would result in appropriate runtime exceptions such as NullPointerException and IllegalArgumentException.
- It should not be used as a replacement to error messages.
- If you do not want any error to arise in any situation, skip using assertion.
- It should not be used on command-line arguments.
- If the user provides errors, assertions should not be used to check arguments in public methods. Instead, error handling should be used.
In-Demand Software Development Skills
How to Disable Assertions?
The following commands are used to disable assertion in Java:
java –da Test
Or
java – disableassertions Test
where Test is the name of the Java file.
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Ways to use Assertion in Java
Example 1: Java assertion
public class Main {
public static void main(String args[]) {
String[] weekdays = {“Mon”, “Tue”, “Wed”,”Thur”,”Fri”};
assert weekdays.length == 2;
System.out.println(“There are ” + weekdays.length + ” weekdays in a week”);
}
}
Output
The following output is achieved when assertions are disabled and the program has no compilation errors.
When the assertions are enabled, we will get the following output:
Exception in thread “main” java.lang.AssertionError
There is another form of assertion statement which is as follows:
assert condition: expression;
This form of assertion statement has an expression that is passed to the AssertionError object’s constructor. If the condition is false, this expression has a value displayed as the error’s detail message. To help in debugging the problem, the detailed massaged captures and transmits the assertion failure information.
Example 2: Java assertion with expression example
public class Main {
public static void main(String args[]) {
String[] weekdays = {“Mon”, “Tue”, “Wed”,”Thur”,”Fri”, “Sat”};
assert weekdays.length == 5: “There are only 5 weekdays in a week”;;
System.out.println(“There are ” + weekdays.length + ” weekdays in a week”);
}
}
Output
Exception in thread “main” java.lang.AssertionError: There are only 5 weekends in a week
As shown in the above example, the expression is passed to the AssertionError object’s constructor. As the assertions are enabled and the assumption is false, an appropriate message is displayed when an exception is thrown. The message helps to diagnose and fix the error that caused the failure of the assertion.
Learn Software Engineering Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Read our Popular Articles related to Software Development
Why Learn to Code? How Learn to Code? | How to Install Specific Version of NPM Package? | Types of Inheritance in C++ What Should You Know? |
Conclusion
In this blog, you have learned how to use assertions to test the program logic. You have also learned why assertions cannot be used as a replacement for exceptions, and you have seen situations where using an exception would be more effective than exception handling.
If you are looking to learn more about Java and move up in your programming career, explore free Java online courses by upGrad, India’s largest online higher education company. Visit upGrad for more information.
If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.