Site icon DataFlair

Java Assert – Why We Use Assertion in Java

Java Assert

Free Java courses with 37 real-time projects - Learn Java

All of us know about if statements. Sometimes when we are programming large applications, it is difficult to write if statements because they take up a lot of space and cause clutter.

Hence it is always best to use assertions which are the same thing as the if statements but they save a lot of space and provide the same functionality.

Assertions in Java

As you might be thinking.. assertions are just different from those of ‘if’ statements in Java.

Sometimes we need to raise custom exceptions for ourselves to properly manage the flow of the program.

The user should not face any hindrance because of that. Hence we use assert statements in Java.

Syntax

assert <expression>

or

assert <expression1>:<expression2>

The second expression is generally the error message that gets thrown after the first expression returns false.

Make sure that the first expression is a boolean expression.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

You also have to enable the asserts in Java because they are disabled by default. This is done to get backwards compatibility in Java.

Asserts got added to Java in version 1.4. Before then it was perfectly normal to have variable and method names as ‘assert’.

But after the assert keyword was introduced, a lot of these programs stopped working because they used a reserved keyword as variable names.

To avoid these difficulties assert is generally disabled by default in Java.

To enable asserts in Java you can use:

java -ea <Compiled Java File>

or

java -enableassertions <Compiler Java File>

You can also disable assertions explicitly by :

java -da <Compiled Java File>

or

java -disableassertions <Compiled Java File>

Although it is often easier to enable/disable assertions for an entire package rather than doing it for each class.

Up until now, you must know that the flag for enabling assertions is -ea and the flag for disabling assertions is -da.

In order to enable or disable assertions for packages, we need to understand a few notations.

So for example if my current package is com.dataflair.assertions and I want to enable assertions for this entire package and all its subpackages my command will be:

java -ea com.dataflair ProgramOne

where “ProgramOne” is the name of the program that I want to execute.

Enough theory, let us get our hands dirty and feet wet!

Java program to illustrate Assertions:

package com.dataflair.assertionsinjava;
public class AssertTest
{
    public static void main(String[] args) {
        int a=20;
        assert a>=30:"Wrong Value";
        System.out.println("This statement will execute only if the value of a is greater than or equal to 30 ");
    }
}

Output:

java -ea AssertTest [17:13:10]Exception in thread “main” java.lang.AssertionError: Wrong Value
at AssertTest.main(AssertTest.java:5)

As you can see the JVM raises the exception with the custom message I provided.

This is useful for debugging scenarios or when a developer wants to know if a variable is really getting a value at a particular point or a method is getting called without having to print stuff to the machine.

Advantages of Using Assertions in Java

There are a ton of advantages of Assertions. let us look at a few of them:

When should you use Java Assertions?

When should you not use Java Assertions?

Difference between Java Assertion and Exceptions

The primary difference between assertions and exceptions is that assertions are disabled by default, but exceptions are enabled everywhere.

Another important thing to note is that assertions are generally useful for checking some part of code which should be logically impossible to execute.

For example, the line after a return statement in a function. You can think of these as sanity checks.

However, exceptions are useful for keeping the flow of the program intact when the user supplies invalid input or there are some invalid operations performed within the program.

Java Assertion Best Practices

There are some commonly used rules which are used when java developers work with assertions.

However, do remember that assertions are disabled by default, so there is no guarantee that your assertion will execute.

Summary

In this article, we came to know about Assertions in Java. We learned how to use it, when to use it and when not to use it.

Although assert is not a very popular topic, it can help reduce boilerplate code in Java. It also helps decrease the ‘if-else’ clutters in the code.

Altogether, it is a cool tool to have in a java developers toolkit.

Exit mobile version