Assertions in Java are used to test assumptions made by the programmer during development. They help detect logical errors early by validating conditions that should always be true.
Java provides the assert keyword to check conditions. If the condition evaluates to false, an AssertionError is thrown.
// Demonstrates basic usage of Java assertions
public class AssertionDemo {
public static void main(String[] args) {
int age = 15;
assert age >= 18 : "Age must be at least 18";
System.out.println("Eligible for voting");
}
}
If assertions are enabled, this program throws an AssertionError because the condition age >= 18 is false. If assertions are disabled, the program runs normally.
Modify the variable and toggle assertions to see how the JVM reacts.
-ea JVM flag