Java Assert Examples

Last Updated : 24 Aug 2026

In Java, the assert keyword performs an assertion operation. The concept of Assertion allows the programmer to verify the assumptions that are taken during the execution of the program. In other words, the process allows checking and verifying the quality and correctness of the taken assumptions that are actually defined within the program. The keyword "assert" was introduced since Java 1.4 version. In the initial time of the invention of the Java programming language itself, the keyword is brought up in the language.

The concept of Assertion is mainly useful for those who generally develop software rather than testing. For every execution of Assertion, the developer expects it to be true. In other cases, if the Assertion fails and returns false, then the compiler shows an error representing the " AssertionError ". The keyword " assert " also makes the code more readable and helps in code optimization. The " assert " keyword is generally assigned with a boolean expression which can be either false or true as the intention of the Assertion operation matches the boolean.

Syntax:

We can also use assert keyword with expressions related to each other.

Syntax:

How can we enable and use Assertion in Java?

In order to use Assertion in Java, we need not import any packages or use any libraries as everything runs with just a single keyword, i.e., " assert ". So, if we want to use and enable assertions in Java, we have to use a command line argument that promotes and enables the keyword " assert ". The command line argument is " -ea " or " -enableassertions" in which the first command line argument is the shorter form of the second command line argument.

After every execution, the assertion operation becomes disable disabled by default, and the process of disabling the keyword is done by the JVM, i.e., Java Virtual Machine. This is done in order to have prior protection from the naming clashes that arise with newer JVM versions. So, before leaving, the JVM automatically disables the assertion validation so that it will not cause any problems during the execution of the next program.

Assertions can be enabled for the specified classes and packages also. For example, let us consider that we have a program containing the main class " Demo " with the file name "Demo". In order to enable the Assertion only for the program containing the class Demo, we can enable it by using the command line argument. Similarly, the assertions can be disabled by using the command line argument " -da " or " - dissableassertions ". Specified classes, packages, and files can also be restricted from using the assertions by disabling the assertions for those specified classes, files, packages, etc. In this way, the enabling and disabling can be done for the Assertion in Java.

Command line argument to enable Assertion in Java:

(or)

Command line argument to enable Assertion for a particular class or a particular file in Java:

(or)

Command line argument to disable Assertion in Java:

(or)

Command line argument to disable Assertion for a particular class or a particular file in Java:

(or)

Why should we use Assertions in Java?

For any task to be handled and executed perfectly, the programmer must know and must be pretty sure about his assumptions made within the entire program. If all the assumptions are wrong, the entire program turns out-graded. So, to make this certainly happen, the assertions must be used in various parts of a program.

AssertionError Handling

The AssertionError is a type of unchecked error. So, the methods that use assertions particularly do not require declaring them, and further calling code should not try to catch an AssertionError. As the AssertionError is an unchecked error, its class extends Error, which extends Throwable. Unlike different exceptions in a program, assertions are usually handled at run-time. These exceptions are meant to indicate unrecoverable conditions. So, recovery or handling of AssertionError must never be attempted.

Important Points to Remember

An Assertion can be disabled by the programmer. We should never assume that they will be included during the execution of a program. So, a programmer must keep certain things in mind while using assertions in their code. They are,

  1. The null values and empty optionals must always be checked while using assertions.
  2. Make use of unchecked exceptions such as IllegalArgumentException or NullPointerException to check input into a public method instead of using assertions.
  3. Assertions can be used in places where the code written will never be executed, such as the default case of a switch statement or after a never-ending loop.
  4. Do not call methods in assertion conditions. Assign the result gained from a method to a local variable and use that variable with the assert keyword.
  5. An assertion can be used to check conditions at the beginning of a method.
  6. The private arguments provided in the developer's code should not be checked using assert as the developer himself may want to check his assumptions about arguments.
  7. An assertion should not be used on command line arguments of a program.

Example: Assertion with Expressions

Java

public class Main {  
    public static void main(String[] args)    {  
        int age = 15;  
        // using assert keyword on two expressions  
        assert age <= 18 : " you cannot hold a license ";  
        System.out.println(" Age of the person is " + age);  
    }  
}  
Compile and Run

Output:

Age of the person is 15

Explanation

In the above program, we used the assert keyword on two expressions, i.e., 18 and " you cannot have a license ". Hence, the Assertion checks if our assumption is true or false by comparing the related expressions. Also, assert is not included in the execution, as we discussed above. In the end, we got our expected output by determining the person's age as 15.

Example: Assert with Method Parameter Validation

Here in this example, a method parameter is validated using assert before to a calculation being carried out. The input integer is checked to make sure it is not negative before the square is calculated. This helps in identifying logical problems early on in the execution of the program.

Java

public class Main {
    static void calculateSquare(int num) {
        // Ensure number is positive
        assert num >= 0 : "Number should be non-negative";
        System.out.println("Square: " + (num * num));
    }
    public static void main(String[] args) {
        calculateSquare(5);
    }
}
Compile and Run

Output:

Square: 25

Example: Assert for Object Null Check

In order to confirm that an object reference is not null before accessing its methods, this example makes use of assert. Rather than permitting a runtime exception like as NullPointerException, an assertion error is thrown if the object is null.

Java

public class Main {
    public static void main(String[] args) {
        String name = null;
        // Proper null check using if condition
        if (name != null) {
            System.out.println(name.length());
        } else {
            System.out.println("Name should not be null");
        }
    }
}
Compile and Run

Output:

Name should not be null

Example: Assert in Loop Condition

To make sure the loop index doesn't go beyond the array length in this case, assert is utilized. When handling dynamic loop circumstances, this type of validation is useful since it avoids unexpected behaviour when traversing an array.

Java

public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40};
        for (int i = 0; i < arr.length; i++) {
            // Ensure index is within bounds
            assert i < arr.length : "Index out of bounds";
            System.out.println(arr[i]);
        }
    }
}
Compile and Run

Output:

10
20
30
40

Example: Assert for Business Logic Check

In this case, assert is used to verify a business rule prior to transaction processing. It determines if the amount taken out is less than or equal to the balance that is available. During development, assertions assist guarantee the program logic operates as intended.

Java

public class Main {
    public static void main(String[] args) {
        double balance = 5000;
        double withdrawAmount = 6000;
        // Ensure sufficient balance before withdrawal
        assert withdrawAmount <= balance : "Insufficient balance";
        System.out.println("Withdrawal Successful");
    }
}
Compile and Run

Output:

Withdrawal Successful