What Are Assertions?

Assert statement In Java is used to test certain assumptions about the state of a program during execution. This helps to easily detect errors and debug the program. An assertion statement in Java is written using the Java assert keyword followed by a boolean expression. If the expression evaluates to true, the assertion passes silently and the program does its job. If it evaluates to false, the assertion fails and an AssertionError is thrown. Let’s have an example of a program with Java assertions.

//Assertion in Java example
public class AssertDemo1 {
   public static void main(String[] args) {
       int x = 5;
       assert x == 5 : "x should be 5";
       System.out.println(x);
   }
}
Here the expression is true, so the program just continues its job. The output is just as it expected to be:
5

The Purpose of Assertions

Assertions serve a specific role in Java development. They help verify that the program is behaving as expected by validating assumptions. Some common use cases include:

✔️ Ensuring certain conditions are met within private methods.

✔️ Checking post-conditions after executing a function.

✔️ Marking unreachable code segments that should never be executed.

Think of assertions as a way to make sure your program follows its expected logic while you’re building it.

Assertions Are for Development, Not Production

One key thing to remember: assertions should not be used for error handling in production. They can be disabled at runtime using the -disableassertions or -da flag, which means they should never be relied upon to enforce critical program logic.

Instead of using assertions for validating user input, command-line arguments, or external data sources, use exceptions like IllegalArgumentException or NullPointerException. Assertions should only be used to catch programming mistakes, not handle runtime errors.

Using Assertions to Verify Assumptions

Assertions are an excellent way to verify assumptions about the state of your program. If you assume that a certain condition must always be true, you can use an assertion to confirm it. If the condition turns out to be false, you know there’s a bug somewhere.


        public void processOrder(Order order) {
            assert order != null : "Order cannot be null";
            System.out.println("Processing order: " + order);
        }
    

This assertion ensures that the processOrder method is never called with a null order.

AssertionError Example

In Java, an AssertionError is a subclass of the Error class and it is thrown when an assertion fails. Assertions in Java are typically used to check that preconditions, postconditions, or invariants hold true. As we said below, an AssertionError is thrown when an assertion statement fails to evaluate to true. Now let's rewrite our program so that the boolean expression is false.

//AssertionError example
public class AssertDemo1 {
   public static void main(String[] args) {
       int x = 5;
       assert x == 7 : "x should be 7";
       //here should be AssertionError
       System.out.println(x);
   }
}
Well, we run it and the output is…
5
Something definitely went wrong in our example! We should have an AssertionError here because our x is 5 and the assertion expects it to be 7. What’s wrong here? It's important to note that Java assertions can be just disabled in the JVM, so they shouldn’t be used as the only means of error checking in a program. They are useful for debugging and testing, but shouldn’t be relied on for production code. So to use assertions, you need to enable them using the vm -ea (or -enableassertions) option. If you are working with command line, you can use next command for your program AssertDemo1:
java -ea AssertDemo1
if you enable assertions and rerun the same program you’ll get the next:
Exception in thread "main" java.lang.AssertionError: x should be 7 at AssertDemo1.main(AssertDemo1.java:4)
That’s the point.

How to enable exceptions in IntelliJ IDEA

  1. Go to Run menu → Edit Configurations....
  2. Enter the -ea parameter in the line VM options
Java Assertions - 1Now the assertions are enabled and you can use them.

Assertions for unit testing in Java

In Java, unit testing is a technique that involves testing individual modules of code to make sure they work correctly. Java Assertions - 2Assertions are commonly used in unit testing in Java to verify that the tested code is working as expected. In unit testing, a unit of code, for example a particular method, is tested in isolation to ensure that it works correctly under different conditions and inputs. Let’s have an example. Here we’ve got a simple calculator for addition, subtraction, multiplication and division 2 integers.

public class MyMath {

   public static int add (int a, int b) {
       return a + b;
   }

   public static int sub (int a, int b) {
       return a - b;
   }

   public static int mult (int a, int b) {
       return a*b;
   }

   public static double div (int a, int b) {
       return a/b;
   }
}
Of course, there are many questions about this implementation (for example, what happens if we add the largest int to another number), but for now we will leave this implementation as it is. Now let's write a class in which we will test the methods of the myMath class with the help of unit tests. True, only two of them. In fact, you can write tests that check arguments for validity, whether a method handles special cases, and so on. But here we will limit ourselves to just a couple of tests for demonstration purposes.

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyMathTesting {
   @Test
   public void testAdd() {
       MyMath calculator = new MyMath();
       int sum = calculator.add(2, 3);
       assertEquals(5, sum);
   }

   @Test
   public void testSub() {
       MyMath calculator = new MyMath();
       int sub = calculator.sub(5, 2);
       assertEquals(3, sub);
   }

}
The assertEquals method is an assertion that checks whether two values are equal. If the values are not equal, an AssertionError will be thrown, indicating that the test has failed. Using assertions in unit tests can help you catch bugs and ensure that your code is working correctly under different conditions and inputs. Try to add such tests for division and multiplication yourself. It is not difficult.

Most common Practices for Using Assertions in Java

Assertions are a great tool in Java for catching bugs early, but like any tool, they should be used wisely. If misused, they can lead to unintended consequences in production code. Let’s explore where not to use assertions, when they are useful, and how to apply them effectively.

Where Not to Use Assertions

Avoid using assertions in public methods to validate arguments. Assertions can be disabled at runtime, which means crucial checks might not run. If you're handling user input, command-line arguments, or configuration parameters, exceptions should be used instead.

Assertions should also not replace proper error handling. They are designed for debugging, not for managing application failures. When unexpected conditions arise in production, exceptions provide a more reliable way to handle them.

When to Use Assertions

Private methods are a great place for assertions since they are only accessed within the same class. Using assertions to validate internal logic helps catch mistakes before they propagate.

Post-condition checks are another great use case. If a method has strict requirements for what it should return, an assertion can ensure the output meets expectations.

Assertions are also helpful for marking unreachable code. If there’s a situation in your logic that should never occur, an assertion can serve as a safeguard. Here’s an example:


        int getNumberType(int number) {
            if (number > 0) return 1;
            if (number < 0) return -1;
            assert false : "Unexpected case: number is zero";
            return 0; 
        }
    

Best Practices for Using Assertions

Never rely on assertions being enabled. Since they can be turned off at runtime, they should not be used for critical application logic. Always write meaningful assertion messages. If an assertion fails, a descriptive message makes debugging much easier.

Use assertions primarily during development and testing. They should not replace runtime validation in production code. When working with assertions, think of them as an extra layer of protection rather than a replacement for structured error handling.