assert Keyword Usage and Examples
Learn how to use the Java assert keyword to perform runtime checks during development. Understand syntax, examples, output, and common mistakes beginners make.
This reference explains assert Keyword Usage and Examples through its syntax, examples and boundaries. Use the linked course lessons when the surrounding Java concepts are unfamiliar.
Use this reference
Identify the documented behavior, read a complete example and check its inputs before applying it.
assert Keyword in Java
The assert keyword in Java is used to perform sanity checks during development. Assertions are like internal self-checks in your code. They're especially useful for catching bugs early by making sure certain conditions are always true at runtime.
What Is the Purpose of Using assert ?
Think of assertions as a form of internal documentation that actively runs and alerts you when something unexpected happens. If an assertion fails, the program throws an AssertionError and stops execution at that point. Assertions are typically used during development and testing, not in production environments.
Basic Syntax of assert
assert condition;
Or with a custom error message:
assert condition : "Error Message";
How to Enable Assertions in Java
By default, assertions are disabled in the JVM. You must explicitly enable them using the -ea flag while running the program:
java -ea YourClassName
Simple Example Without Error Message
public class AssertDemo {
public static void main(String[] args) {
int age = 20;
assert age > 18;
System.out.println("Age is valid");
}
}
Age is valid
Here, since age > 18 is true, the assertion passes and execution continues normally.
Example With Assertion Failure
public class AssertFailDemo {
public static void main(String[] args) {
int age = 16;
assert age > 18;
System.out.println("This line won't be printed");
}
}
Exception in thread "main" java.lang.AssertionError
The program stops with an AssertionError because the condition age > 18 is false.
Using Assertions With Custom Error Messages
public class AssertMessageDemo {
public static void main(String[] args) {
int number = -5;
assert number >= 0 : "Number must be non-negative";
System.out.println("Number is " + number);
}
}
Exception in thread "main" java.lang.AssertionError: Number must be non-negative
The error message provides context, which is extremely helpful during debugging.
Where Should You Use Assertions?
- Validating internal logic during development
- Ensuring preconditions/postconditions in methods
- Verifying state transitions in algorithms
However, avoid using assertions to validate user input or parameters in public methods. These should be handled with proper exception handling instead.
Common Pitfalls and Misuse
- Forgetting to enable assertions at runtime using
-ea - Using assertions for production-critical checks
- Using assertions to change program state (e.g., modifying variables inside assertions)
Practical Use Case Example
public class Calculator {
public static int divide(int a, int b) {
assert b != 0 : "Divider cannot be zero";
return a / b;
}
public static void main(String[] args) {
int result = divide(10, 2);
System.out.println("Result: " + result);
// This will cause an AssertionError
divide(10, 0);
}
}
Result: 5
Exception in thread "main" java.lang.AssertionError: Divider cannot be zero
Summary
- The
assertkeyword helps you catch bugs during development. - Assertions should not replace proper validation in production code.
- Always run your Java program with
-eato see assertion effects. - Use custom messages to make debugging easier.
When Not to Use assert
Never rely on assertions for input validation, file I/O checks, or network operations. These are part of the contract with external systems or users and should be managed using proper error handling mechanisms.
Using this reference
Check the example’s types, inputs and documented behavior before copying it into an application. Some APIs require external libraries, files or platform services; consult their setup notes.
Related explanations: Java Data Types - Primitive and Non-Primitive, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide.
Reference checks are optional and do not count toward course progress.