Overview
The assert statement lets you document and test assumptions about your program. You do so by writing boolean expressions that should always be true. If they don't, and you have enabled the execution of your assumptions, the assertion will throw an AssertionError. JarFiller uses assertions a lot, as it is a quick and concise way of showing the reader the expected result of an operation.
Java supports the assert statement since version 1.4 (in other words, practically forever).
Assert Syntax
The syntax of assertions is very simple. You just write the assert keyword followed by the expression. For example:
assert 2 + 2 == 4;
The assertion's expression will only be executed if assertions have been enabled (more). By default, they are disabled. If assertions are enabled and the expression is false, an AssertionError will be thrown.
You can add a second expression argument expression to the assert statement, separated by a colon (':') from the first argument. Its value will be shown to the user if the assertion failed and is used to show the wrong value or cause of the error:
String a = "abcdefg";
assert a.contains("c") : a;
If a would not contain a "c" (which obviously can never happen in this example), the assertion would abort the execution by throwing an AssertionError and specify the value of a as reason.
Compute length of the hypotenuse (Pythagorean theorem):
static double getLengthOfHypotenuse(double a, double b) {
double squareSum = a*a + b*b;
assert squareSum >= 0; // always positive (more)
return Math.sqrt(squareSum);
}
Split string into space-separated words, capitalize the words, and put the string together:
String capitalizeWords(String sentence) {
if (sentence.trim().length() == 0) // no empty sentences (more)
return sentence;
String r = "";
for (String word: sentence.trim().split("\\s+")) { // split into words (more)
assert word.length() >= 1; // no empty strings (more)
r += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
}
return r.trim();
}
Return an opening hour for the given date - 8 for weekdays, 9 on Saturday, 11 on Sunday:
static int getOpeningHour(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
int weekday = cal.get(Calendar.DAY_OF_WEEK);
if (weekday >= Calendar.MONDAY && weekday <= Calendar.FRIDAY)
return 8;
else if (weekday == Calendar.SATURDAY)
return 9;
else if (weekday == Calendar.SUNDAY)
return 11;
else {
assert false; // all days considered? (more)
return 0; // still needed (more)
}
}
Side-effects are assertions that modify data and thus influence the rest of the program. Then the program may behave differently depending on whether assertions are enabled or not. Side-effects should be avoided. The following line shows a simple assert statement with side-effect:
int a = 4;
assert a++ != 0; // bad: side-effect
System.out.println("a=" + a);
Depending on whether assertions are enabled or not, the program will either print "a=4" or "a=5".
Enabling Assertions
Java will only execute assertions if you enable them with the -ea option:
> java -ea ClassToRun
Unlike other programming languages, it is not possible in Java to tell the compiler to exclude assertions from the binary. javac will always compile them into the classes.
The Java runtime can also be configured to execute assertions only for specific packages or classes. See the Java launcher documentation for more details.