Site Navigation

Apr 29, 2013

Java Assertions in a Nutshell

Duke Waving

After answering a question about Java Assertions today, a short how to seems a good idea.

Assertions - An easy way to put optional tests in your Java source.

Enabling Assertions - By default assertions are disabled, to enable them add a switch to the java command line.

java -ea MyProgram

-ea is short for -enableassertions.

Writing an Assertion - There are two possible formats.

assert x > 1;


assert x > 1:"My special error message here";

If the statement is true, nothing happens. If false, an exception is thrown and the program stops executing.

Testing if Assertions are Enabled - The easy way is to just put a false assertion in your Main method.

assert false==true
Post a Comment

Favorite Links Feed