The assert command in Java looks like this:
void main() {
assert (1 == 2);
}
If you compile and run this program with the -ea (enable assertions) option, it will crash on the assert line and report an assertion violation, because 1 == 2 will evaluate to false.
$ javac Assert.java
$ java Assert # no -ea, nothing happens
$ java -ea Assert
Exception in thread "main" java.lang.AssertionError
at Assert.main(Assert.java:2)
If you give an assert an expression that evaluates to true, the program will continue executing as normal.
You can use assertions to check that your preconditions are satisfied in a function — it's better to crash and stop the program if the environment doesn't match your expectation than continue to run and potentially do something wrong.
For the first part of this course, we will use assert for testing.