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. 

Syntax

The following are two ways in which assertion is carried out in Java:

1. assert expression;

2. assert expression1: expression2;

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);

   }

}

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

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:

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. 

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.

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.

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.

Land on Your Dream Job

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN SOFTWARE DEVELOPMENT
LEARN MORE

0 replies on “What is Assertion in Java? How to use Assertion in Java”

×