📜  java assert - Java (1)

📅  最后修改于: 2023-12-03 15:15:55.333000             🧑  作者: Mango

Java Assert

Assert statements in Java are used to evaluate an expression which, if found false, terminates the current execution with an error message. It helps in debugging the code by identifying the errors in the code more easily. An assert statement should be used to check the program's internal states and invariants.

Syntax

The syntax for assert statement in Java is as follows:

assert expression;
assert expression1 : expression2;

Here, expression is any valid expression which will be tested for truth. If expression is found to be true, then the execution continues normally. Otherwise, the program will end with an AssertionError.

Enabling and Disabling Assertions

Java assertions are typically disabled to improve performance. To enable assert statements in your program, you can use the following command-line option:

java -ea MyClass

Here, "MyClass" is the name of your program's class.

To disable assertions, you can use the following command-line option:

java -da MyClass
Example

Here is an example of an assert statement in Java:

public class MyClass {
    public static void main(String[] args) {
        int x = 10;
        assert x == 5 : "x should be equal to 5";
        System.out.println("x is " + x);
    }
}

In this example, an assert statement is used to check if x is equal to 5. Since the value of x is 10, the assert statement will fail and terminate the program with an AssertionError.

Conclusion

Java assert statements can be a useful debugging tool for checking a program's internal logic and invariants. They should be used sparingly and selectively, as they can slow down program execution if left enabled.