Curriculum
Assertions in Java are a way for developers to add a sanity check to their code. An assertion is a statement that is assumed to be true at a certain point in the code, and if it is not true, an AssertionError
is thrown. Assertions can be used to detect bugs early in the development cycle and improve the reliability of code.
Here is an example of how to use assertions in Java:
public class MyClass { public static void main(String[] args) { int x = 10; int y = 20; assert x < y : "x is not less than y"; // Some code that uses x and y } }
In this example, we use the assert
keyword to add an assertion to our code. The assertion checks whether the value of x
is less than the value of y
, and if it is not, an AssertionError
is thrown with the message “x is not less than y”.
We can also use assertions to check for null values or other conditions that should not occur in our code:
public class MyClass { public static void main(String[] args) { String str = null; assert str != null : "String is null"; // Some code that uses the string } }
In this example, we add an assertion to check whether the str
variable is null. If it is null, an AssertionError
is thrown with the message “String is null”.
Assertions can be enabled or disabled at runtime using the -ea
or -da
command line options. By default, assertions are disabled, so it is important to enable them during development and testing to ensure that our code is behaving correctly.
Assertions should not be used as a substitute for proper error handling or input validation. They are intended to be used as a sanity check to catch programming errors early in the development cycle.