The assert
keyword in Java is used to define an assertion, which is a boolean expression that is checked at runtime to ensure that it is always true. If the expression is false, the assert
statement throws an AssertionError
.
Assertions are typically used to test the internal consistency of an application and to ensure that the program is running correctly. They are not meant to be used for input validation or error handling, and they should not be used in production code.
Here is an example of how to use the assert
keyword:
public class AssertExample { public static void main(String[] args) { int x = 10; assert x > 0; // this assertion will pass assert x < 0; // this assertion will fail } }
In this example, the first assert
statement checks that the value of x
is greater than 0
, which is true, so the assertion passes. The second assert
statement checks that the value of x
is less than 0
, which is false, so the assertion fails and an AssertionError
is thrown.
To enable or disable assertions at runtime, you can use the -enableassertions
and -disableassertions
options of the java
command. For example:
java -enableassertions MyClass // enables assertions java -disableassertions MyClass // disables assertions
By default, assertions are disabled in Java. To enable assertions, you need to specify the -enableassertions
option when running the java
command.
You can also enable or disable assertions for a specific package or class using the -ea
and -da
options. For example:
java -ea:com.example.package // enables assertions for the com.example.package package java -da:com.example.package // disables assertions for the com.example.package package java -ea:com.example.MyClass // enables assertions for the com.example.MyClass class java -da:com.example.MyClass // disables assertions for the com.example.MyClass class