In Java, assertions are a way to test assumptions about your program during runtime. They are primarily used for debugging purposes and help catch programming errors early. An assertion evaluates a boolean expression, and if the expression evaluates to false
, the JVM throws an AssertionError
.
Syntax
assert condition;
or
assert condition : expression;
- condition – a boolean expression that you expect to be
true
. - expression – an optional message or object that is displayed if the assertion fails.
Example
public class AssertionExample {
public static void main(String[] args) {
int age = 15;
// Basic assertion
assert age > 18 : "Age must be greater than 18";
System.out.println("Age is valid: " + age);
}
}
Explanation:
- The assertion
assert age > 18 : "Age must be greater than 18";
checks ifage
is greater than 18. - Since
age
is 15, the assertion fails and throws anAssertionError
with the message:"Age must be greater than 18"
. - If the condition were
true
, the program would continue normally.
How to Enable Assertions
By default, assertions are disabled in Java. To enable them, use the -ea
flag when running your program:
java -ea AssertionExample
Key Points
- Assertions are used for testing assumptions, not for handling runtime errors like exceptions.
- They are disabled by default in production, so they shouldn’t replace normal error handling.
- Assertions can include a message for better debugging.