Programs

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.

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.

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.

What 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.

How 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.

How 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.

Want to share this article?

Land on Your Dream Job

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks