House3272
House3272

Reputation: 1037

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.

Upvotes: 5

Views: 14237

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136112

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

Upvotes: 1

Eric J.
Eric J.

Reputation: 150198

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

Upvotes: 10

Related Questions