Java Assertions

In Java, an assertion is a statement that allows you to test your assumptions about your program at runtime. Assertions are typically used for debugging and testing purposes, and are not meant to be used in production code.

Here is an example of using assertions in Java:

public class Main {
    public static void main(String[] args) {
        int x = 5;

        // Make an assertion about the value of x
        assert x > 0;

        // The assertion will pass and the program will continue to execute
        System.out.println("x is positive.");
    }
}

In this example, the assertion assert x > 0; tests the assumption that the value of x is greater than 0. If the assertion evaluates to true, the program will continue to execute. If the assertion evaluates to false, the program will throw an AssertionError and terminate.

You can also include a message with your assertion to provide more information about the error:

public class Main {
    public static void main(String[] args) {
        int x = 5;

        // Make an assertion with a message
        assert x > 0 : "x is not positive.";

        // The assertion will pass and the program will continue to execute
        System.out.println("x is positive.");
    }
}

In this example, the assertion assert x > 0 : "x is not positive."; includes a message that will be displayed if the assertion fails.

To enable assertions in your Java program, you can use the -enableassertions or -ea command-line option when running the program. By default, assertions are disabled in Java.