Card 06/ 09
All 9 cards
GotchaDifficulty: Intermediate1 min
Why 5 + 3 * 2 % 4 Is Not Read Left to Right
A pricing expression that produced 16 in your head and 7 in the log. Nothing is wrong with the arithmetic; the expression was not grouped the way it reads.
System.out.println(5 + 3 * 2 % 4);7*, / and % bind tighter than + and -, and among themselves they go left to right. So Java grouped it as 5 + ((3 * 2) % 4): six, then six modulo four is two, then five plus two.
| Level | Operators |
|---|---|
| Tightest | ++ -- and a cast |
* / % | |
+ - | |
< > <= >= | |
== != | |
&& | |
| Loosest | ||, then = |
Do not memorise the table. Write the brackets you mean, even where they are redundant — the next reader gets the grouping for free, and nobody has ever been caught out by a bracket that was not needed.