bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java assert Keyword

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java assert Keyword?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

public ___ Main {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The assert keyword evaluates a boolean expression and throws an AssertionError exception if the expression evaluates to false .
Definition and Usage
Java assert Keyword

❮ Java Keywords

Example

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 evaluates a boolean expression and throws an AssertionError exception if the expression evaluates to false . When the exception is thrown we say that the assertion failed.

An optional expression can be added which will be used as the exception message if the assertion fails.

Assertions are disabled by default. assert statements are ignored unless assertions are enabled.

The purpose of assertions is to clearly mark where a program is doing something unintended when debugging and testing a program.

❮ Java Keywords

Previous

Java Keywords

Next

Java abstract Keyword