5

Which logical operator get "prioritized" or "read" ahead of the other, so to say.

For example:

if( x=y || y=y && x=x ){}

is java reading this as: One of these two: (x=y||y=y), AND (x=x)

or as: Either (x=y) or (y=y AND x=x)


Sounds like something that would have been asked or at least easy to find, but alas, "and" + "or" are keywords to Google.

5
  • Any reason you couldn't just test it yourself? Mar 26, 2013 at 3:05
  • 5
  • 3
    In cases like this, always use brackets for reading clarity
    – Krease
    Mar 26, 2013 at 3:06
  • 1
    Also be sure to use == instead of just = for your comparisons (is that just a typo in the question?)
    – Krease
    Mar 26, 2013 at 3:09
  • @Evan, that's a very good point. What I was working on confuse me to the point of a migraine, not that I fully remember at present.
    – House3272
    Mar 26, 2013 at 15:58

2 Answers 2

10

The operator && has a higher precedence than ||, so && will be evaluated first.

http://introcs.cs.princeton.edu/java/11precedence/

Still, many programmers will not remember that fact. It is clearer and more maintenance-friendly to use parenthesis to specifically state the order of evaluation intended.

Note that in your code you write

x=y

that is actually the assignment operator, not the equality operator. Presumably you intend

x==y
3
  • 3
    Seconded on using ( ) to separate logical statements. This makes code far easier to read, and makes your meaning transparent.
    – ajp15243
    Mar 26, 2013 at 3:09
  • Dang, you said everything I wanted to say in addition to linking the order of precedence. +1
    – Krease
    Mar 26, 2013 at 3:12
  • Thanks! I am aware on both accounts, was just asking. Besides, x==x doesn't make much sense anyhow.
    – House3272
    Mar 26, 2013 at 15:59
1

x=y || y=y && x=x can work only if both x and y are boolean, since = is assignment, and it is equivalent to y || y && y because you assigned x=y in as in first operation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.