The assert keyword, as the name suggests, makes a statement about the code. It is used to indicate what is held all the time - or at least it should be true!
The assert keyword is followed by a boolean value ( true or false ) or an expression that must be evaluated at run time that returns a boolean value.
assert true; assert 1 == 1;
If for any reason the boolean expression evaluates to false, an AssertionError is thrown.
When you use it, you make a clear expression about the state of your program at a given point, which makes it easier for the reader to read through your code.
There is a programming paradigm called a contract program in which code fragments contain statements about the preconditions that must be met correctly for them to be executed properly, and afterwords that are guaranteed to be sure after they are executed. You can use the assert keyword to implement this.
For example, if you write a method that calculates the square root of a number, it will only work for numbers that are greater than or equal to zero, and the result is guaranteed to satisfy the same conditions:
public double sqrt(final double x) { assert x >= 0 : "Cannot calculate the square root of a negative number!" double result = ...; assert result >= 0 : "Something went wrong when calculating the square root!" return result; }
The most interesting aspect of the statements is that you can ask the compiler to remove them from the bytecode (using the -disableassertion argument) so that you don't get any execution penalty during production execution. For this exact reason, it is fundamental that the expression to be evaluated does not cause side effects , i.e. The expression should look like a pure mathematical function. Otherwise, the behavior of your program may change if the compiler removes your statements.
Finally, if statements are compiled into bytecode, they can be read using software that will automatically generate tests that try to break your code. It may be helpful to find errors earlier!