From: Eric Blake (e_blake@email.com)

Subject: Re: Operator Precedence

View: Complete Thread (20 articles)

Original Format

Newsgroups: comp.lang.java.programmer

Date: 2001-04-13 19:21:30

PST "Scott D. Isaac" wrote:

> ..

> 12. Short-circuit: &&

> 13. Short-circuit: || ..

>

> However, I have found the JLS (section 15) to be vague about precedence.

> While this is the order in which they are presented, there is no mention

> that that is the order of precedence.

It is explicitly stated within the grammar of chapter 15, but is lacking

in the grammar of chapter 18, as well as the descriptive text of chapter

15. Hopefully the 3rd edition JLS will rectify this and make the

chapter 18 grammar express precedence, as well as describe it better in

the description.

>

> So, what's my beef you ask?

>

> Through experimentation, I have found that 12 and 13 are at the same level

> of precedence. This contradicts what I have seen written and the JLS is

> silent on this matter.

The difference in precedence is observable when the first term evaluates

as true.

With (a||b)&&c, c must be evaluated if a is true. However, with

a||(b&&c), the entire (b&&c) term is never evaluated, because ||

short-circuits.

So, if || and && have equal precedence, a||b&&c is equivalent to

(a||b)&&c, since they group left-to-right; you would get a side-effect

from evaluating c in 6 of the 8 input cases, and a true result in only 3

of the 8.

However, since && has a higher precedence, a||b&&c is equivalent to

a||(b&&c), and you only get a sige-effect from c in 2 of the 8 input

cases, and a true result in 5 of the 8.

Here's a program to print out all the cases.

This program outputs (with some post-formatting applied):

false false false a b false a b false a b false

false false true a b false a b false a b false

false true false a b c false a b c false a b c false

false true true a b c true a b c true a b c true

true false false a true a c false a true

true false true a true a c true a true

true true false a true a c false a true

true true true a true a c true a true

--

Eric Blake