Signup/Sign In

Java Assertions

Assert is a keyword in Java that allows us to test an assumption. A Boolean expression is used with the assert keyword.

The assertion(combination of assert keyword and the Boolean expression) is initially considered as true. If the assertion is false, then we will get an AssertionError.

The AssertionError is an unchecked exception. We do not need to declare it with the throws keyword in the method. We also don't need to use try-catch blocks with this error.

We can follow any one of the following syntaxes to create an assertion.

In the second case, the expression two is returned with the AssertionError. It helps us in understanding the cause of the error and assists us in debugging our code accordingly.

assert <Boolean-expression>;
assert <expression-1> <expression-2>;

Enabling and Disabling Assertions

By default, assertions are disabled in Java. In early versions of Java, we could use the word assert for variable and method names. This could lead to inconsistencies. However, we can easily enable assertions by using the -enableassertions option or the -ea option.

java -enableassertions :<package-name>... :<class-name>
java -ea:<package-name>... :<class-name>

Disabling them is also pretty straightforward. We can use the -disableassertions or the -da option for this.

java -disableassertions :<package-name>... :<class-name>
java -da:<package-name>... :<class-name>

Assertion Examples

Let's create an assertion statement that assumes that the length of an array is 5. When the length is equal to 5, we don't get any AssertionError.

public class Demo
{
	public static void main(String args[])
	{
		int[] arrOfLengthTwo = {6, 8, 2, 1, 1};
		assert arrOfLengthTwo.length == 5;
		System.out.print("Array Length is: " + arrOfLengthTwo.length);
	}
}


Array Length is: 5

Let's alter the array length and run the code. We should get an AssertionError in this case.

public class Demo
{
	public static void main(String args[])
	{
		int[] arrOfLengthTwo = {2, 1, 1};
		assert arrOfLengthTwo.length == 5;
		System.out.print("Array Length is: " + arrOfLengthTwo.length);
	}
}


Exception in thread "main" java.lang.AssertionError
at Demo.main(Demo.java:6)

Let's also add a message that will be displayed if the error is thrown.

public class Demo
{
	public static void main(String args[])
	{
		int[] arrOfLengthTwo = {2, 1, 1};
		assert arrOfLengthTwo.length == 5 : "Array Length is Not 5";
		System.out.print("Array Length is:" + arrOfLengthTwo.length);
	}
}


Exception in thread "main" java.lang.AssertionError: Array Length is Not 5
at Demo.main(Demo.java:6)

When to use Assertions in Java?

Assertions are used in unreachable parts of the code. This makes sure that if the program tries to execute the unreachable code, then an AssertionError is thrown.

public static void main(String[] args)
{
	while(true)
	{
		System.out.println("Reachable part of the code");
	}
		
	//Unreachable
	assert false;
}

Assertions are also used to make the default case of a switch statement unreachable.

public static void main(String[] args)
{
	int booleanInt = 0;
	switch (booleanInt) {
		case 0:
	        System.out.println("False");
		    break;
		case 1:
		    System.out.println("True");
		    break;
		default:
			assert false : "boolean integer can only be 0 or 1"; 
    }
}

We can also use assertions to imply underlying assumptions or to make sure that the comments provide correct information.

public static void main(String[] args)
{
	int num = 10;
	if(num > 0)//Positive number
		System.out.print("Positive");

	else//Negative number
	{
		assert num < 0 : "Number is zero";
		System.out.print("Negative");
	}
}

When not to use Assertions?

  • Assertions are used in a lot of different places. However, we should avoid using them to check inputs to public methods. If we get an AssertionError in such cases, then it will be difficult to pin actual errors.
  • We should also not call methods inside our assertions. Instead, we can use a temporary variable to store the result and use this variable inside the assertion. This is done to ensure that the operation is performed irrespective of whether the assertions are enabled or not.

Summary

Assertions are a great way of detecting errors and debugging our code. They are mostly used during the testing phase of the software. Assertions also make our code more readable. Assertions are disabled in Java, but we can easily enable them. In this tutorial, we learned how to use assertions in Java.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.