English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)

Java Reader/Writer

Java Other Topics

Java Assertions (Assert)

In this tutorial, we will learn about Java assert statements (Java assertions) with examples.

In Java, assertions help detect errors by testing the code we believe to be correct.

Assertions are performed using the assert keyword.

The syntax is:

assert condition;

Here, condition is a boolean expression, and we assume it is true during program execution.

Enable assertions

By default, assertions are disabled at runtime and ignored.

To enable assertions, we use:

java -ea:arguments

Or

java -enableassertions:arguments

If assertions are enabled and the condition is true, the program will execute normally.

However, if the condition is calculated as false when assertions are enabled, the JVM will throw an AssertionError, and the program will stop immediately.

Example1: Java assertions

class Main {
  public static void main(String args[]) {
    String[] weekends = {"Friday", "Saturday", "Sunday"};
    assert weekends.length == 2;
    System.out.println("这个星期有 ", + weekends.length + "    weekends");
  }
}

Output result

This week has 3 weekends

We get the above output because the program has no compilation errors, and assertions are disabled by default.

After enabling assertions, we get the following output:

Exception in thread "main" java.lang.AssertionError

Another form of assertion declaration

assert condition : expression;

In this form of assertion statement, the expression is passed to the constructor of the AssertionError object. If the condition is false, the value of the expression is displayed as detailed information of the error.

Detailed messages are used to capture and transmit assertion failure information to help debug problems.

Example2: Example of Java assertion with expression

class Main {
  public static void main(String args[]) {
    String[] weekends = {"Friday", "Saturday", "Sunday"};
    assert weekends.length==2 : "There are only 2 weekends in a week";
    System.out.println("There are ", + weekends.length + "    weekends in a week");
  }
}

Output result

Exception in thread "main" java.lang.AssertionError: There are only 2 weekends in a week

From the above examples, it can be seen that the expression is passed to the constructor of the AssertionError object. If our assumption is incorrect (false) and assertions are enabled, an exception will be thrown and an appropriate message will be displayed.

This message helps diagnose and fix errors that cause assertion failures.

Enable assertions for specific classes and packages

If we do not provide any parameters to the assertion command-line switches

java -ea

Assertions will be enabled in all classes except system classes.

We can also use parameters to enable assertions for specific classes and packages. The parameters that can be provided to these command-line switches are:

Enable assertions in class name

To enable assertions for all classes in program Main

java -ea Main

Only one class is enabled

java -ea:AnimalClass Main

This only allows assertions to be used in the AnimalClass of the Main program.

Enable assertions in package name

To enable assertions for the package com.animal and its sub-packages

java -ea:com.animal... Main

Enable assertions in an unnamed package

Enable assertions in an unnamed package in the current working directory (when we do not use the package statement).

java -ea:... Main

Enable assertions in system classes

To enable assertions in system classes, we use different command-line switches:

java -esa:arguments

or

java -enablesystemassertions:arguments

The parameters that can be provided to these switches are the same.

Disable assertions

To disable assertions, we use:

java -da arguments

or

java -disableassertions arguments

To disable assertions in system classes, we use:

java -dsa:arguments

or

java -disablesystemassertions:arguments

The arguments that can be passed when assertions are disabled are the same as when they are enabled.

Advantages of assertions

  1. Detect and correct errors quickly and efficiently.

  2. Assertions are checked only during development and testing. They are automatically removed from production code at runtime, so they do not slow down the execution speed of the program.

  3. It helps to remove boilerplate code and make the code more readable.

  4. Refactor and optimize code to enhance confidence in its correct operation.

When to use assertions

1.Unreachable code

Unreachable code is the code that will not be executed when we try to run the program. Use assertions to ensure that the unreachable code is actually unreachable.

Let’s take an example.

void unreachableCodeMethod() {
  System.out.println("Reachable code");
  return;
  // Unreachable code
  System.out.println("Unreachable code");
  assert false;
}

Let’s take a look at a switch statement example without a default case.

switch (dayOfWeek) {
  case "Sunday":
    System.out.println("It’s Sunday!");
    break;
  case "Monday":
    System.out.println("It’s Monday!");
    break;
  case "Tuesday":
    System.out.println("It’s Tuesday!");
    break;
  case "Wednesday":
    System.out.println("It’s Wednesday!");
    break;
  case "Thursday":
    System.out.println("It’s Thursday!");
    break;
  case "Friday":
    System.out.println("It’s Friday!");
    break;
  case "Saturday":
    System.out.println("It’s Saturday!");
    break;
}

The above switch statement indicates that the days of the week can only be the following7of the values. No default case means that the programmer believes that one of these cases will always be executed.

However, some assumptions may actually be incorrect and certain cases may not have been considered yet.

Assertions should be used to check this assumption to ensure that the default switch condition is not reached.

default:
    assert false: dayofWeek + " is invalid day"

Throw an AssertionError if the value of dayOfWeek is not a valid date.

2.Record assumptions

To record their basic assumptions, many programmers use comments. Let's take an example.

if (i % 2 == 0) {
    ...
} else { // We know (i % 2 == 1)
    ...
}

Please use assertions instead.

As the program grows, comments may become outdated and out of sync. But we will have to update the assert statements; otherwise, they may also fail due to valid conditions.

if (i % 2 == 0) {
   ...
} else {
    assert i % 2 == 1 : i;
    ...
}

When not to use assertions

1.Check parameters in public methods

Users can provide parameters in public methods.

Therefore, if assertions are used to check these parameters, the condition may fail and cause an AssertionError.

It is better to let it throw appropriate runtime exceptions and handle these exceptions than to use assertions.

2.Evaluate expressions that affect program operation

Do not call methods or evaluate exceptions that may affect the program's operation under assertion conditions.

Let's take a list example, where the weekdays list contains the names of all days of the week.

ArrayList<String> weekdays = new ArrayList<>(Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"));
ArrayList<String> weekends = new ArrayList<>(Arrays.asList("Sunday", "Saturday"));
assert weekdays.removeAll(weekends);

Here, we try to remove elements Saturday and Sunday from the ArrayList weekdays.

If assertions are enabled, the program can run normally. However, if assertions are disabled, elements in the list will not be deleted. This may cause the program to fail.

Instead, assign the result to a variable and then use that variable for assertions.

ArrayList<String> weekdays = new ArrayList<>(Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"));
ArrayList<String> weekends = new ArrayList<>(Arrays.asList("Sunday", "Saturday"));
boolean weekendsRemoved = weekdays.removeAll(weekends);
assert weekendsRemoved;

In this way, we can ensure that all weekends are removed from weekdays, regardless of whether assertions are enabled or disabled. As a result, it will not affect future program operations.