Question

what is the difference between the 2 cases at runtime execution ?

private void doStuff() {
assert (y > x);
// more code assuming y is greater than x
}

private void doStuff() {
assert (y > x): "y is " + y + " x is " + x;
// more code assuming y is greater than x
}
Was it helpful?

Solution

The assert statement takes the following form

assert Expression1 : Expression2 ;

The Java Language Specification states

Otherwise, execution continues by making a choice based on the value of Expression1:

  • If the value is true, no further action is taken and the assert statement completes normally.

  • If the value is false, the execution behavior depends on whether Expression2 is present:

    • If Expression2 is present, it is evaluated.

      • If the evaluation completes abruptly for some reason, the assert statement completes abruptly for the same reason.

      • If the evaluation completes normally, an AssertionError instance whose "detail message" is the resulting value of Expression2 is created.

        • If the instance creation completes abruptly for some reason, the assert statement completes abruptly for the same reason.

        • If the instance creation completes normally, the assert statement completes abruptly by throwing the newly created AssertionError object.

    • If Expression2 is not present, an AssertionError instance with no "detail message" is created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top