Java
Programming
Assertions
Coding Best Practices
Software Development

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.

Browse interview questions

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:

java
assert expression;

or

java
assert expression : "Error message";

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:

java
1public void updateQuantity(int newQuantity) {
2    assert newQuantity >= 0 : "Quantity cannot be negative";
3    // Code to update quantity
4}

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:

  1. 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.
  2. Control-Flow Invariants: To check that a particular line of code should never be reached, or a switch statement has covered all possible cases.
  3. Class Invariants: Ensuring the validity of an object's state after the constructor has completed execution.
  4. 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

PropertyDescription
PurposeTo detect developer mistakes during runtime.
Keywordassert
Syntaxassert BooleanExpression; or assert BooleanExpression : ErrorMessage;
Default StateDisabled by default.
EnablingUse -ea or -enableassertions flag.
Use CasesInternal 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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.