0

Quick question. In Java, do AND's take precedence over OR's? For example, how is this code interpreted?

if(statement1 && statement2 || statement3)

Which is this the same as?

if(statement1 && (statement2 || statement3))

or

if((statement1 && statement2) || statement3)

Thanks in advance.

user2029675
  • 245
  • 3
  • 9
  • 8
    I really think this could have either been tested by yourself or researched! – Duncan Jones Jan 31 '13 at 15:58
  • 2
    This is answered by a [2 second Google](https://www.google.co.uk/search?q=java+and+or+precedence). – RB. Jan 31 '13 at 15:58
  • http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – kosa Jan 31 '13 at 15:58
  • 1
    Don't vote to close as "too localized". That is far from true - this question is *in theory* of interest to a very wide audience. Instead, find a suitable duplicate or just downvote for the lack of research. – Duncan Jones Jan 31 '13 at 16:00
  • 1
    possible duplicate of [Java operator precedence guidelines](http://stackoverflow.com/questions/2137690/java-operator-precedence-guidelines) – trashgod Jan 31 '13 at 16:04
  • @DuncanJones Your comment says "don't vote to close as too localized". The text box under this question says "closed as too localized by ... Duncan Jones". How does that fit together? – us2012 Jan 31 '13 at 16:53
  • 1
    @us2012 The text chosen for the "closed as..." box is the majority choice made by the close voters. Three selected "too localized", trashgod and I selected "exact duplicate". – Duncan Jones Jan 31 '13 at 16:54

3 Answers3

8

Yes. It's pretty easy to find out, the API docs have a table listing the operator precedence: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

However, I think it's a good idea to understand why && should take precedence over || : The former is in many ways a multiplicative action, while the latter is an additive one. Consider two independent events A and B, the probability of (A and B) is p(A)*p(B) while the probability of (A or B) is p(A) + p(B). By analogy with the well-known rule that * takes precendence over +, this explains why logical operators should be evaluated in that way.

us2012
  • 16,083
  • 3
  • 46
  • 62
5

As stated in the Oracle tutorial for operators && has high precedence than ||

Note: & has higher precedence than | which is higher than && and then ||

Operators of equal precedence are evaluated left to right (except for assignment operators). e.g. 1 + 2 + "3" is not the same as 1 + (2 + "3") as the order matters. Similarly 100 / 10 / 2 != 100 / (10 / 2)

For assignment operators a *= b += 5 is the same as a *= (b += 5)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Yes, according to the documentation, && takes precedence over || (unless you use parentheses).

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104