In Java, an
assertion is a statement used to test assumptions in the program logic during development.
If the assumption is false, the program throws an
AssertionError, helping detect bugs early.
Assertions are usually disabled by default and can be enabled during runtime with the
-ea flag.
Syntax to write an assertion:
assert expression;
or
assert expression : errorMessage;
Example:
int age = 20;
assert age>18 : "Age must be above 18";
If the condition is false, it throws an error with the message.
Assertions are useful for debugging and testing internal logic but should not replace exception handling.