Java Assert – Why We Use Assertion in Java

Get Job-ready: Java Course with 45+ 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.

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.

  • “nameofPackage…” – This will allow you to enable or disable packages for the mentioned package and its subpackages.
  • “…” – This will allow you to enable or disable assertions in the current package in the working directory. Use this if your package is unnamed.

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:

  • Checks if a particular block of code is reachable or not.
  • Checks if the assumptions made by the developer are correct.
  • These can also be useful to check method invocations.
  • Assertions can check if the control is reaching the beginning of a method.
  • They can also check the state of an object.

When should you use Java Assertions?

  • If you have a switch case with no default case, then you might want to use assertions. This is because you might think that it is logically impossible for the variable to have any other value other than your cases. You can use an assert to check if your logical assumption is correct.
  • You can also use assert statements to check if the control flow is correct or not. For example, if you have a function that returns a value, you may want to put an assert statement. However, you may get a ‘non-reachable’ code error. Hence it is always better to throw a ‘newAssertionError()’.
  • You can also use them as arguments of a private method.

When should you not use Java Assertions?

  • You should not use assertions the same way you use exceptions. They should not replace error messages.
  • When the errors are due to the user’s invalid input or due to an error in the program itself, they should be handled by the error handling block and not by assertions.
  • You should not use assertions on command line arguments.

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.

  • You should not use assertions to check for valid parameters. Instead, use exceptions.
  • You should assert for null values whenever you can.
  • It is not a good practice to connect the method call directly with the assert method. One workaround is that you can store the return of that method to a local variable. You can then use that variable to assert for conditions.
  • It is advisable to use assertions where the program might never reach. This is done to check if the program is performing abnormally.

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.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

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