1

Why this boolean statement is true?

a= 10;
b = 0;
7 < a || a == b && b > 9 - a / b

Since anything divided by 0 is error

  • 4
    Because `7 < a` and then the `||` isn't evaluated because the first condition is true. – Elliott Frisch May 15 '17 at 13:07
  • 1
    Hint: how do you expect that expression to be evaluated? – Jon Skeet May 15 '17 at 13:08
  • good question. according to [Operators](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) && has precedence over ||. So why would || short circuit before &&? – John Mercier May 15 '17 at 13:14
  • Possible duplicate of [&& (AND) and || (OR) in IF statements](https://stackoverflow.com/questions/1795808/and-and-or-in-if-statements) – Turtle May 23 '17 at 08:48
  • @JohnMercier This is weird (your link), in java && and || have the same "precedence level", and are executed from left to right. – Turtle May 23 '17 at 08:50

3 Answers3

7

Since the first operand of the OR (||) operator (a > 7) evaluates to true, it short circuits and nothing else is evaluated. Therefore the entire expression evaluates to true.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Beat me to the clock :( – Turtle May 15 '17 at 13:09
  • 5
    IDK why you got immediately 6 upvotes for such very easy question! Oh I forgot, you may be a moderator :D – Yahya May 15 '17 at 13:12
  • @Yahya Mostly because it is explain simply in one line too. Other answers are not that easy to read – AxelH May 15 '17 at 13:17
  • 1
    this is not a reason @AxelH also the rest of the answers explain that in one line maybe better, maybe because he is the first one who answer?? no idea, `?` i'm like Yahya – Youcef LAIDANI May 15 '17 at 13:19
  • 1
    @YCF_L to be fair, I didn't upvote any because I believe there is duplicate for that question ;) – AxelH May 15 '17 at 13:26
1

7 < a returns true. Since it's a || after, the rest isn't executed.

This is because true || false is true, and true || true is true too, so evaluing the second member is but a waste of time.

Turtle
  • 1,626
  • 16
  • 26
1

Your OR-Operator || uses lazy evaluation or short-circuit evaluation. This means, since the very first expression 7 < ais true, it won't evaluate any other statements including the one with a division by zero, since java already found something true.

If you actually want to get an error, you can use this OR-Operator | which should enforce the evaluation of all statements. Most only use it as a bitwise-operator, but its also a non-short-circuit version of ||. For a more in-depth look at || vs. |, look here.

For example,

boolean c = (7 < a | a == b && b > 9 - a / b);

will cause an ArithmeticExcption, as expected.

Community
  • 1
  • 1
ptstone
  • 478
  • 7
  • 17