← Back to Chapters

Assertions in Java

✅ Assertions in Java

? Quick Overview

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.

? Key Concepts

  • Introduced in Java 1.4
  • Used mainly for debugging and testing
  • Disabled by default at runtime
  • Enabled using JVM flags

? Syntax / Theory

Java provides the assert keyword to check conditions. If the condition evaluates to false, an AssertionError is thrown.

? View Code Example
// 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");
}
}

?️ Live Output / Explanation

If assertions are enabled, this program throws an AssertionError because the condition age >= 18 is false. If assertions are disabled, the program runs normally.

? Interactive Simulator

Modify the variable and toggle assertions to see how the JVM reacts.

int age = ;
Enable Assertions (-ea)
assert age >= 18 : "Validation Failed";
C:\Users\Dev> java AssertionDemo
...

? Tips & Best Practices

  • Use assertions for internal logic checks, not user input validation
  • Never use assertions to handle business logic
  • Enable assertions during testing using -ea JVM flag
  • Avoid assertions in public methods of libraries

? Try It Yourself

  • Enable assertions and observe program behavior
  • Write an assertion for array index validation
  • Compare assertions with exception handling