An assertion is defined as a claim or assumption. In programming, there are cases when we, as programmers, know that a certain variable takes a specific value(s) at a particular line of code. We usually represent such a claim using comments in our code.
An assertion in Java is one single line of code which checks a certain boolean expression and throws a AssertionError if that expression is false. We say that an assertion has failed in this case.
Note: Assertions are disabled by default in Java. Include
-ea
command in your Java interpreter (or search specifically for your IDE on the web).
There are two ways to write an assertion using the assert keyword.
assert expression;
We can pass our own message as any type of variable (other than void) which will be shown in the stack trace in case the expression was false.
assert expression : "Invalid value";
int x = 3;if(x <= 2) {// ...}else { // x > 2// ...}
int i = 5;while(i > 0){if(i == 2){ // Can be any condition which you think will be surely met.return;}i--;}// My program should not reach this place.
Free Resources