-3

A book I'm working from states :

The short-circuit operators are nearly identical to the logical operators, & and |, respectively, except that the right-hand side of the expression may never be evaluated if the final result can be determined by the left-hand side of the expression

To test this out I tried

int y = 1;

boolean x = false | (y < 4);

System.out.print(x);    //true

Which printed out true as expected.

however

int y = 1;

boolean x = false || (y < 4);

System.out.print(x);    //true

also prints out true which seems to contradict the book "the right-hand side of the expression may never be evaluated if the final result can be determined by the left-hand side of the expression".

I was assuming x would take the value of false as the final result can be determined from the left hand side alone

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Kevin
  • 15
  • 2
  • 6
  • The right hand side is only evaluated if the result can not be determined from the left hand side. – marstran Jun 21 '17 at 10:17
  • 1
    You need to look at the RH operand to evaluate `false || rh`, since its value is equal to `rh`. – Andy Turner Jun 21 '17 at 10:18
  • An or expression is true when one of it operands is true. So after testing the first, which equals false, it tests the second, which evaluates to true. It would short circuit if the first evaluated to true. – Koekje Jun 21 '17 at 10:18
  • Perhaps [this application](https://ideone.com/qD9dy3) will make it clearer. Both expressions mean `true OR true`, which both ultimately evaluate to `true`. However, the logical OR is clever enough to know that `true OR {anything}` will always evaluate to `true`. Therefore, it doesn't bother calling the function `foo` and the string "logical or" is never printed. – Michael Jun 21 '17 at 10:23

1 Answers1

1

I was assuming x would take the value of false as the final result can be determined from the left hand side alone

No, the final result cannot be determined by the left hand side alone - since the left operand is false, the right operand must be evaluated too (since false OR something == something).

On the other hand, if the left operand was true, the result of the OR operator would be true, and the right operand could be ignored.

You should understand that short-circuit operators should give the same result as their non-short circuited counterparts (except for cases where evaluating the right operand may throw an exception and the short-circuited operators can determine the result by the left operand alone).

There would be no scenarios in which the short circuited operator returns false and the corresponding non-short circuited operator returns true or vice versa.

Eran
  • 387,369
  • 54
  • 702
  • 768