Computers do exactly what you tell them to do โ not what you meant. If you misunderstand order of operations, your program can run without errors but give the wrong answer.
PEMDAS tells us the order to solve math expressions:
( )Important:
8 + 4 ร 2
Steps:
4 ร 2 = 88 + 8 = 16โ Answer: 16
Java follows rules similar to PEMDAS, but with more operators. This is called operator precedence.
( )++ -- + - !* / %+ -< > <= >=== !=&&||=Note: Java has more operators than this list, but these are the ones youโll use most often.
Java evaluates expressions using precedence rules, one step at a time.
int result = 10 + 6 / 2;
Steps:
6 / 2 = 310 + 3 = 13โ result = 13
int result = (10 + 6) / 2;
Steps:
10 + 6 = 1616 / 2 = 8โ result = 8
Java includes modulus, which finds the remainder.
int x = 10 % 3;
10 รท 3 = 3 remainder 1โ x = 1
If both numbers are integers, Java cuts off decimals. (This is called integer division.)
int x = 5 / 2;
2.52โ x = 2
To fix:
double x = 5.0 / 2;
โ x = 2.5
When operators have the same precedence, Java evaluates left to right.
int x = 20 / 5 * 2;
Steps:
20 / 5 = 44 * 2 = 8โ x = 8
boolean answer = 10 > 5 + 3;
Steps:
5 + 3 = 810 > 8โ answer = true
When in doubt, use parentheses.
| Concept | Math (PEMDAS) | Java |
|---|---|---|
| Parentheses | โ | โ |
| Multiplication / Division | โ | โ |
| Addition / Subtraction | โ | โ |
| Modulus (%) | โ | โ |
| Logical operators | โ | โ |
| Integer division | โ | โ |
What is the output?
System.out.println(8 + 12 / 4 * 2);
Steps:
12 / 4 = 33 * 2 = 68 + 6 = 14โ Output: 14