2

cond && cond op cond

op can be && or ||

Qn- For short circuit (&&) operator if the first cond is false then right part (whole) is not evaluated or just the second cond after && is not evaluated

Also why the result of following two expressions different?

(2 > 3 && 5 < 2 || 3 > 2) => True

(2 > 3 && 5 < 2 | 3 > 2) => False

Can't we use short circuit operator and standard operators in a single expression...?

madth3
  • 7,275
  • 12
  • 50
  • 74

2 Answers2

3

The results are different because | and || have different precedence.

Specifically, | has higher precedence than &&, whereas || has lower precedence than &&.

          System.out.println(2 > 3 && 5 < 2 || 3 > 2);    // true
          System.out.println(2 > 3 && 5 < 2 | 3 > 2);     // false
          System.out.println(2 > 3 && (5 < 2 | 3 > 2));   // false
          System.out.println((2 > 3 && 5 < 2) | (3 > 2)); // true
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • thanks..is there any problem in using | or & as logical operators? – PRAKHAR SHARMA Dec 11 '12 at 20:18
  • Not that I know of, but you have to be careful because once you get into the different precedences, you have to make sure you know what comes first and how it will be read by the server. – Felix Guo Dec 11 '12 at 20:20
  • 1
    @PRAKHARSHARMA I'd recommend against using `|` and `&` as logical operators because 1) they don't short-circuit, so code will be unnecessarily executed, and 2) most people don't use them that way, so your code will be unconventional. – matts Dec 11 '12 at 20:27
  • 1
    I just asked similar question and I got decent answers: http://stackoverflow.com/questions/15089890/do-and-make-any-sense-in-java To cut it short, most of people agree that using | and & to enforce business logic may lead to bugs and unclean code. So it is discouraged, on some rare occasions there are useful usage. – CsBalazsHungary Feb 26 '13 at 14:47
1

Your results differ because your second case uses | instead of ||. | is the bit-wise or, which is different from the logical or.

Now you say short-circuit expressions vs. standard expressions, but in many languages short-circuit expressions are the default (or only way) logical expressions are evaluated.

If by "standard" you mean bit-wise operators like & or |, then you can mix and match them with logical operators, although the results may not be what you expect.

RonaldBarzell
  • 3,822
  • 1
  • 16
  • 23
  • i agree that | is a bitwise operator but it can alse be used as a non short circuit ..am I wrong? – PRAKHAR SHARMA Dec 11 '12 at 20:08
  • 1
    Ok... I recommend not using "standard" because if anything, the short circuit ones are the standard. Also, don't think of | as a non short-circuit. It does something different than ||. – RonaldBarzell Dec 11 '12 at 20:08