What is Assertion in Java? How to use Assertion in Java
Updated on Nov 24, 2022 | 7 min read | 5.8k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 24, 2022 | 7 min read | 5.8k views
Share:
Table of Contents
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
The following are two ways in which assertion is carried out in Java:
1. assert expression;
2. assert expression1: expression2;
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:
The assertion in Java is used to:
Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)
if ((y & 1) == 1)
{ }
else // y must be even
{ assert (y % 2 == 0); }
The assertion in Java is used at the beginning of the method and after the method invocation.
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:
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?
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.
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.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources