Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java assert Keyword
Usage and Examples



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?

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

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

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M