Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 767
House3272 Avatar asked Mar 26 '13 03:03

House3272


2 Answers

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

like image 22
Evgeniy Dorofeev Avatar answered Nov 15 '22 11:11

Evgeniy Dorofeev


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
like image 141
Eric J. Avatar answered Nov 15 '22 09:11

Eric J.