Search code examples
javaassert

"assert" in java


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?


Solution

  • Assertions are used to test assumptions about running code. They differ from if checks in a number of ways:

    • Assertions are disabled at runtime, by default
    • Assertions shouldn't be used for argument checking, or anything else that is required for normal operation of your program.
    • Assertions often test assumptions about state you might have previously seen in a comment. For example, you might use an assertion to verify that you're not violating a loop invariant or that a method's preconditions have been satisfied.

    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.