What are some real life examples to understand the key role of assertions?
Assertions are disabled by default. To enable them we must run the program with -ea
options (granularity can be varied). For example, java -ea AssertionsDemo
.
There are two formats for using assertions:
assert 1==2; // This will raise an AssertionError
.assert 1==2: "no way.. 1 is not equal to 2";
This will raise an AssertionError with the message given displayed too and is thus better. Although the actual syntax is assert expr1:expr2
where expr2 can be any expression returning a value, I have used it more often just to print a message.