Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"assert" in java [duplicate]

Tags:

java

assert

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?

like image 731
Ariel Grabijas Avatar asked Feb 03 '26 12:02

Ariel Grabijas


1 Answers

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.

like image 150
Wayne Avatar answered Feb 06 '26 09:02

Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!