user1539343
user1539343

Reputation: 1669

Need help understanding this following boolean expression in an if statement

Found from the Kathie Sierra book on OCA/OCP Java SE 7 Programmers I & II study guide:

int x = 2;
int y = 5;
if ((x > 3) && (y < 2) | doStuff()) {
    System.out.println("true");
}

This now prints ... nothing! Because the preceding code (with one less set of parentheses) evaluates as though you were saying, "If (x > 3) is not true, and either (y < 2) or the result of doStuff() is true, then print true. So if (x > 3) is not true, no point in looking at the rest of the expression" Because of the short-circuit &&, the expression is evaluated as though there were parentheses around (y < 2) | doStuff().

In my understanding, the operators && and || has the same precedence and evaluated from left to right. So in this case, the expression (x > 3) && (y < 2) should still be evaluated first. Please explain.

Update: My mistake. It is indeed a "|" instead of a "||".

Upvotes: 0

Views: 88

Answers (1)

Makoto
Makoto

Reputation: 106508

Well, I wouldn't necessarily expect it to print anything. The condition x > 3 && y < 2 is false for the given values of x and y.

I've had a moment now to reflect on the operator precedence, and basically, regardless of what doStuff says (true or false), if x > 3 evaluates to false, it's not printing anything.

Effectively, this expression:

(x > 3) && (y < 2) | doStuff()

is equivalent to:

(x > 3) && (y < 2 | doStuff())

...and since x > 3 is false for the given x value, the entire expression evaluates to false. Here, && will short-circuit the expression, without calling doStuff.

Upvotes: 5

Related Questions