views:

330

answers:

2

Misunderstanding Java operator precedence is a source of frequently asked questions and subtle errors. I was intrigued to learn that even the Java Language Specification says, "It is recommended that code not rely crucially on this specification." JLS §15.7 Preferring clear to clever, are there any useful guidelines in this area?

Here are a number of resources on the topic:

Additions or corrections welcome.

+5  A: 

As far as the Real World is concerned, it's probably fair to say:

  • enough programmers know that multiplication/division take precendence over addition/subtraction, as is mathematically the convetion
  • hardly any programmers can remember any of the other rules of precedence

So, apart from the specific case of */ vs +-, I'd really just use brackets to explicitly define the precedence intend.

Neil Coffey
Did you mean brackets or parenthesis'?
Anthony Forloney
The reason programmers hardly can remember is because each language is slightly different.
Thorbjørn Ravn Andersen
They *are* slightly different in different languages, but even programmers of a single language generally don't memorise the list. @Anthony -- in my world, parentheses are a type of bracket.
Neil Coffey
I was just thinking in terms of operators precedence, I thought it was parentheses that determined precedence. I just wasn't sure if you meant the `{` block when referring to brackets
Anthony Forloney
@Neil: All oarentheses may be brackets, but not all brackets are parentheses.
Anonymous
finnw
@Neil - when talking to IT folks, it is best to stick to conventional IT / typographic terminology. '()' are parentheses (or round brackets), '[]' are brackets (or square brackets) and '{}' are braces (or curly brackets).
Stephen C
Stephen -- could this be a US thing by any chance? In UK English, even among programmers, it's really OK to call () "brackets". If you say "brackets", I really don't think anyone will think you mean [] unless you specify "square" brackets. Really!!
Neil Coffey
In the context of operator precedence, "brackets" can really only mean "round brackets".
Mark
"hardly any programmers can remember any of the other rules of precedence". So true.
fastcodejava
+2  A: 

Another related source of bugs is how rounding errors accumulate. Not an operator precedence order issue per se, but a source of surprise when you get a different result after rearranging operands in an arithmetically-equivalent way. Here's a sun.com version of David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic.

iter