Card 06/ 09

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.

java
System.out.println(5 + 3 * 2 % 4);
text
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.

The operators you meet daily, tightest binding first
LevelOperators
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.