Search code examples
javatestingjvmassert

Overhead of Java assert call


How is it that a Java assert call to verify the value of a variable can be a no-op? Wouldn't operations be required to compare the expected value to the actual value?


Solution

  • It is not a no-op. A system property determines whether assertions are enabled or disabled. The assert statement gets compiled into an if statement which checks if assertions are enabled then executes the actual assertion check.

    Check out the oracle doc on assertions which covers how it could be accomplished before the keyword (1.3) and how the keyword works in 1.4+.