Possible Duplicate:
What does assert do?
What is "assert"? What for is "assert" key-word used for? When and where can it be useful?
This is an example of method from red-black tree implementation:
public Node<K,V> grandparent() {
assert parent != null; // Not the root node
assert parent.parent != null; // Not child of root
return parent.parent;
}
i don't know what for "assert" is used in this code. Can't we type this code in some other way, with - for example - "if's" instead?
Assertions are used to test assumptions about running code. They differ from if
checks in a number of ways:
if
statements are used for control flow, argument checking, etc. Assertions are used to reason about the correctness of internal methods, etc, during development and debugging.
In practice, these two lines:
assert parent != null; // Not the root node
assert parent.parent != null;
...enforce that neither parent
or parent.parent
is null
when this method is called. If either of those assertions fail, the program will throw an AssertionError
.