What does the Java assert keyword do, and when should it be used?

Praveen picture Praveen · May 3, 2010 · Viewed 474k times · Source

What are some real life examples to understand the key role of assertions?

Answer

Ophidian picture Ophidian · May 3, 2010

Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned on by default.

An example:

public Foo acquireFoo(int id) {
  Foo result = null;
  if (id > 50) {
    result = fooService.read(id);
  } else {
    result = new Foo(id);
  }
  assert result != null;

  return result;
}