Java operator precedence guidelines
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:
- JLS Operators
- JLS Precedence
- Java Glossary
- Princeton
- Oracle Tutorial
- Conversions and Promotions
- Java Operator Precedence
- Evaluation Order and Precedence
- Usenet discussion
Additions or corrections welcome.
As far as the "Real World" is concerned, it's probably fair to say:
- enough programmers know that multiplication/division take precedence over addition/subtraction, as is mathematically the convention
- 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 intended.
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.