Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The assert statement

The assert statement: The assert statement checks an internal assumption and throws AssertionError on failure, optionally carrying the value of the expression after the colon.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

assert

The assert statement checks an internal assumption and throws AssertionError on failure, optionally carrying the value of the expression after the colon.

Use assert for invariants and conditions that correct code must always satisfy during tests run with -ea.

Assertions are disabled by default, so never use them for public API argument validation or put required side effects inside their expressions.

The message expression is evaluated only when the condition is false and assertions are enabled; status can be configured per class, package, or class loader.

Main has assertions off as main-enabled=false, but Checked is enabled and its assert ends with caught=negative:-1.

Examples

public class Main {
  static class Checked { static void verify(int n){ assert n>=0:"negative:"+n; } }
  public static void main(String[] args) throws Exception {
    if(args.length==0){
      System.out.println("main-enabled="+Main.class.desiredAssertionStatus());
      String java=ProcessHandle.current().info().command().orElseThrow();
      var child=new ProcessBuilder(java,"-ea","-cp",System.getProperty("java.class.path"),"Main","child").inheritIO().start();
      if(child.waitFor()!=0) throw new IllegalStateException("child failed");
    } else {
      try { Checked.verify(-1); } catch(AssertionError ex) { System.out.println("caught="+ex.getMessage()); }
    }
  }
}

Result

main-enabled=false
caught=negative:-1

Main has assertions off as main-enabled=false, but Checked is enabled and its assert ends with caught=negative:-1.

Sources