Assertions in Java are a useful tool for developers to test assumptions about their program’s behavior during runtime. When an assertion fails, it throws an AssertionError
, which helps in identifying bugs early in the development process.
Enabling Assertions
By default, assertions are disabled. To enable assertions, use the -ea
or -enableassertions
option when running your Java program.
or
java -enableassertions:arguments
true
, the program executes normally.But if the condition evaluates to false
while assertions are enabled, JVM throws an AssertionError
, and the program stops immediately.
Assertion Syntax
expression
evaluates to false
, an AssertionError
is thrown.Example of Assertions
Ex:
1 2 3 4 5 6 7 8 9 10 11 | public class AssertionExample { public static void main(String[] args) { int x = 1; assert x > 0 : "x must be greater than 0"; System.out.println("x is: " + x); x = -1; assert x > 0 : "x must be greater than 0"; System.out.println("x is: " + x); } } |
When running the above code with -ea
, the program will throw an AssertionError
at the second assertion when x
is -1
.
Ex:
1 2 3 4 5 6 7 | class Main { public static void main(String args[]) { String[] weekends = {"Friday", "Saturday", "Sunday"}; assert weekends.length == 2; System.out.println("There are " + weekends.length + " weekends in a week"); } } |
Output:
1 | There are 3 weekends in a week |
We get the above output because this program has no compilation errors and by default, assertions are disabled.
After enabling assertions, we get the following output:
1 | Exception in thread "main" java.lang.AssertionError |
When to Use Assertions
- Checking Preconditions: Ensure that the input conditions to a method are valid.
- Checking Postconditions: Ensure that the conditions after executing a method are correct.
- Checking Invariants: Ensure that the state of an object is valid throughout its lifecycle.
- Checking Unreachable Code: Ensure that certain code paths are never executed.