How/Can you use both && and || in the same if statement condition?

11,068

Solution 1

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

Solution 2

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

Share:
11,068
House3272
Author by

House3272

Updated on June 04, 2022

Comments

  • House3272
    House3272 almost 2 years

    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.

    • Evan Trimboli
      Evan Trimboli about 11 years
      Any reason you couldn't just test it yourself?
    • Jayan
      Jayan about 11 years
    • Krease
      Krease about 11 years
      In cases like this, always use brackets for reading clarity
    • Krease
      Krease about 11 years
      Also be sure to use == instead of just = for your comparisons (is that just a typo in the question?)
    • House3272
      House3272 about 11 years
      @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.
  • ajp15243
    ajp15243 about 11 years
    Seconded on using ( ) to separate logical statements. This makes code far easier to read, and makes your meaning transparent.
  • Krease
    Krease about 11 years
    Dang, you said everything I wanted to say in addition to linking the order of precedence. +1
  • House3272
    House3272 about 11 years
    Thanks! I am aware on both accounts, was just asking. Besides, x==x doesn't make much sense anyhow.