assert
is not the same as methods like assertTrue()
from testing libraries. It is a reserved keyword and a unary operator in Java.This operator does not return anything but takes a boolean expression as its argument. If the expression evaluates to
false
, the assertion is considered failed, and an AssertionError
is thrown. It's like a shorthand for a combination of if
and throw
with a fixed exception type.In Java versions prior to 4,
assert
was not a keyword. To maintain backward compatibility, assertion checks are disabled by default—program logic should never rely on assert
!Assertions can be enabled using the
-ea
or -enableassertions
flags with the java
command. Specific classes and packages where assertions are enabled can also be specified. There's an opposite flag,-da
(-disableassertions
), and these flags can be used in combination.Assertions are mainly used for additional checks of object state invariants and as safeguards in code that should never be executed. An
AssertionError
usually indicates a programmer error.Additionally, the
assert
operator has a syntax for passing a detailMessage
parameter to the AssertionError
constructor:assert 2*2==5 : "two times two is not five!";