Open In App

Assertions in Java

An assertion allows testing the correctness of any assumptions that have been made in the program. An assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError. It is mainly used for testing purposes during development. 

The assert statement is used with a Boolean expression and can be written in two different ways.



First way: 

assert expression;

Second way:  



assert expression1 : expression2;

Example:




// Java program to demonstrate syntax of assertion
import java.util.Scanner;
 
class Test {
    public static void main(String args[])
    {
        int value = 15;
        assert value >= 20 : " Underweight";
        System.out.println("value is " + value);
    }
}

Output
value is 15

After enabling assertions:

Output:  

Exception in thread "main" java.lang.AssertionError: Underweight

Enabling Assertions  

By default, assertions are disabled. We need to run the code as given. The syntax for enabling assertion statement in Java source code is: 

java –ea Test

Or 

java –enableassertions Test

Here, Test is the file name.

Disabling Assertions

The syntax for disabling assertions in java is: 

java –da Test

Or  

java –disableassertions Test

Here, Test is the file name.

Why use Assertions 

Wherever a programmer wants to see if his/her assumptions are wrong or not. 

if ((x & 1) == 1) {

}
else // x must be even
{
    assert (x % 2 == 0);
}

Assertion Vs Normal Exception Handling

Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state a code expects before it starts running or the state after it finishes running. Unlike normal exception/error handling, assertions are generally disabled at run-time. 

Where to use Assertions  

Where not to use Assertions  

Example:




// Java program to demonstrate assertion in Java
public class Example {
    public static void main(String[] args)
    {
        int age = 14;
        assert age <= 18 : "Cannot Vote";
        System.out.println("The voter's age is " + age);
    }
}

Output
The voter's age is 14

 


Article Tags :