How/Can you use both && and || in the same if statement condition?
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
House3272
Updated on June 04, 2022Comments
-
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 about 11 yearsAny reason you couldn't just test it yourself?
-
Jayan about 11 years
-
Krease about 11 yearsIn cases like this, always use brackets for reading clarity
-
Krease about 11 yearsAlso be sure to use == instead of just = for your comparisons (is that just a typo in the question?)
-
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 about 11 yearsSeconded on using
( )
to separate logical statements. This makes code far easier to read, and makes your meaning transparent. -
Krease about 11 yearsDang, you said everything I wanted to say in addition to linking the order of precedence. +1
-
House3272 about 11 yearsThanks! I am aware on both accounts, was just asking. Besides, x==x doesn't make much sense anyhow.