What are assertions in Java and when should they be used?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Assertions in Java provide a means for developers to test assumptions made by the program. An assertion is a statement in Java that enables testing of assumptions about your program's behavior. If an assumption proves false, the assertion fails, throwing an AssertionError. Ideally used to catch programming errors early in the development lifecycle, assertions aid in debugging by pointing out exactly where a system fails to meet an expected condition.
How to Use Assertions
Assertions are implemented with the assert keyword. This keyword is followed by a boolean expression and an optional error message. The syntax for using assertions is either:
or
When the expression evaluates to false, the assertion fails, and the Java runtime system throws an AssertionError. When provided, the "Error message" string is passed to the AssertionError constructor, which helps developers understand what went wrong.
Example Usage
Here’s a simple code snippet demonstrating the use of assertions:
In this example, if newQuantity is negative, the assertion will fail, throwing an AssertionError with the message "Quantity cannot be negative".
Enabling Assertions
By default, assertions are disabled in Java to avoid a performance penalty during runtime. Assertions can be enabled through command line options:
- To enable assertions for the entire application use:
java -ea <ClassName> - To enable assertions for specific classes or packages use:
java -ea:com.example.package... <ClassName>
When to Use Assertions
Assertions should be used as a development tool to detect logical errors in code. They are not intended to replace error handling or to validate arguments passed from a user or an external system. Here are appropriate uses for assertions:
- Internal Invariants: Checking for conditions which should always hold regardless of the system state. For example, checking if a linked list is cyclic could be an invariant if your application logic dictates it should never be the case.
- Control-Flow Invariants: To check that a particular line of code should never be reached, or a switch statement has covered all possible cases.
- Class Invariants: Ensuring the validity of an object's state after the constructor has completed execution.
- Pre-conditions and Post-conditions: Ensuring that "contractual" obligations are met in the code.
Caveats of Using Assertions
- Not a Replacement for Runtime Checks: Since assertions can be disabled, they should not be used for argument checking in public methods or any method exposed to user input.
- Performance Impact: Although minimal, assertions do have a runtime cost when enabled, as they need to evaluate the expression provided.
Summary Table
| Property | Description |
| Purpose | To detect developer mistakes during runtime. |
| Keyword | assert |
| Syntax | assert BooleanExpression; or assert BooleanExpression : ErrorMessage; |
| Default State | Disabled by default. |
| Enabling | Use -ea or -enableassertions flag. |
| Use Cases | Internal invariants, control-flow checking, class invariants, pre-conditions, and post-conditions. |
Conclusion
Assertions in Java are a useful tool for developers, designed specifically to catch and diagnose programming errors quickly. However, they should not be used for handling runtime errors that can arise from external inputs or user interactions. Properly used, assertions help maintain code quality and ensure that your assumptions about your code's behavior stand the test of time and development cycles.
Related reading
- What are connecting characters in Java identifiers?
- What are functional interfaces used for in Java 8?
- What are major differences between C and Java?
- What are major differences between C and Java?
- What are Runtime.getRuntime.totalMemory and freeMemory?
- What are spring-boot-starter jars?
- What are static factory methods?
- What are the -Xms and -Xmx parameters when starting JVM?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.