Card 06/ 09
Operator Precedence: Why 5 + 3 * 2 % 4 Is 7
Read left to right it gives 0; Java groups it differently and prints 7.
Precedence is the order in which Java groups the parts of an expression: *, / and % bind tighter than + and -, so they are applied first, whatever order the line is written in. An expression is therefore not read left to right.
A pricing expression that gives 0 if you work through it from left to right, 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% gives the remainder of a division, and it sits with * and /. Among themselves those three go left to right, so Java grouped the line as 5 + ((3 * 2) % 4): six, then six modulo four is two, then five plus two.
| Level | Operators |
|---|---|
Tightest (a cast is a type in brackets, such as (int)) | ++ -- 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.
← → move through sections and cards