Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconWhat is Assertion in Java? How to use Assertion in Java

What is Assertion in Java? How to use Assertion in Java

Last updated:
20th May, 2021
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
What is Assertion in Java? How to use Assertion in Java

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;

Ads of upGrad blog

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:

Source

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:

  1. 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. 
  2. It should not be used as a replacement to error messages.
  3. If you do not want any error to arise in any situation, skip using assertion.
  4. It should not be used on command-line arguments.
  5. 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.

Ads of upGrad blog

Read our Popular Articles related to Software Development

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is assertion in Java?

In Java programming language, assertion is a method used for ensuring that some requirements should be followed. The assertion failure in Java is considered as compilation error, i.e. if there are any assertions in your code, the code won't be compiled, and you will get error message. This feature of Java enables you to protect your code from unexpected or unwanted run-time errors. The Java assert statement allows you to test invariants of your program at run time. Assertions are normally used to check that the code is not entering an invalid state. In other languages you may see contract methods or pre/post conditions used for this purpose.

2How to handle exceptions in Java?

An exception is a runtime error, meaning it occurs while the program is running, not during compilation. The exception is thrown when an error has occurred and the program cannot continue. You can handle exceptions in three different ways: Ignore the exception and allow the program to exit. Use the throw keyword to rethrow the exception. Use the try-catch block to handle the exception. You can log or print the exception and then let the program exit. You can use the exit keyword to terminate the program. You can use the throw keyword to rethrow the exception. You can use the try-catch block to handle the exception. There's a catch block that accepts the exception in its argument. There's a finally block that runs whether an exception is thrown or not.

3How does try-catch work in Java?

try-catch is a mechanism in Java that allows you to define a scope in which you can deal with runtime errors in a controlled manner. It also ensures that the flow of execution doesn't stop completely when an error is encountered. try and catch are two keywords used to implement exception handling. Whenever an error occurs in your program, the try block will be executed, and the error will then be handled by the catch block.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907173
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902296
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902674
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Password Validation in JavaScript [Step by Step Setup Explained]
48976
Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to registe
Read More

by Rohan Vats

13 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74112
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43493
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
229999
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

10 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon