Jump to content
Wikibooks The Free Textbook Project

Java Programming/Keywords/assert

From Wikibooks, open books for an open world

This is the current revision of this page, as edited by Dirk Hünniger (discuss | contribs) at 11:02, 28 June 2024 (preparing for pdf generation with LaTeX). The present address (URL) is a permanent link to this version.

Revision as of 11:02, 28 June 2024 by Dirk Hünniger (discuss | contribs) (preparing for pdf generation with LaTeX)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

assert is a Java keyword used to define an assert statement. An assert statement is used to declare an expected boolean condition in a program. If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws an AssertionError Assertions may be declared using the following syntax:

Computer code
assertexpression1[:expression2];

expression1 is a boolean that will throw the assertion if it is false. When it is thrown, the assertion error exception is created with the parameter expression2 (if applicable).

An example:

Computer code
assertlist!=null&&list.size()>0:"list variable is null or empty";
Objectvalue=list.get(0);

Assertions are usually used as a debugging aid. They should not be used instead of validating arguments to public methods, or in place of a more precise runtime error exception.

Assertions are enabled with the Java -ea or -enableassertions runtime option. See your Java environment documentation for additional options for controlling assertions.

AltStyle によって変換されたページ (->オリジナル) /