Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

assert

Example

Leverage the assert statement to verify the validity of expressions:

public class Main {
  public static void main(String[] args) {
    // Enable assertions
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    loader.setDefaultAssertionStatus(true);
    
    // Run the assert example
    AssertExample example = new AssertExample();
    example.run();
  }
}
 
class AssertExample {
  public void run() {
    int a = 12;
    try {
      assert a == 12; // Assertion without a fail message
      assert a == 12 : "a is not 12";
      assert a == 15 : "a is not 15";
    } catch (AssertionError e) {
      System.out.println(e.getMessage());
    }
 
}
}

Definition and Usage

The assert keyword checks a boolean expression and throws an AssertionError if the expression evaluates to false. When this exception is thrown, it indicates that the assertion has failed.

You can add an optional expression to serve as the exception message if the assertion fails.

By default, assertions are disabled, and assert statements are ignored unless assertions are explicitly enabled.

The purpose of assertions is to clearly indicate where a program behaves unexpectedly during debugging and testing.