What javac does
assert
A static flag set from desiredAssertionStatus(), checked before each assertion.
assert compiles to a test of a synthetic static field, $assertionsDisabled, which the static initialiser sets from Class.desiredAssertionStatus(). With assertions off, the default, each assert costs a getstatic and an ifne that skips it, and the JIT compiler removes even that because the field is final.
The source
// assert: a static flag set from desiredAssertionStatus(), and an AssertionError.
public class Asserts {
static int half(int n) {
assert n % 2 == 0 : "odd: " + n;
return n / 2;
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- The message is built only when the assertion fails, after the test, so an expensive message costs nothing while it holds.
- A failed assertion is an ordinary
newAssertionError andathrow. - With
--release 8the message is built with a StringBuilder; from 11 on, withinvokedynamic.
Asserts.class
static int half(int n)
javac --release 8