The order of operations works similarly how they work in mathematics. The order of operation is as follows:
- parenthesis (
( )
)
- mutliplication, division, and modulus working from left to right (
*
, /
, %
)
- addition and subtraction working from left to right (
+
and -
)
Your Turn
Example 1
- Predict the result of the following expression.
- Check to see if you are correct by running it in the Java Playground.
Explanation:
- The first operation is multiplication
5 * 7
, which is 35
. Leaving us with 3 + 35 % 4
.
- The second operation is modulus division
35 % 4
, which is 3
. Leaving us with 3 + 3
.
- The last operation is addition
3 + 3
, which is 6
.
- So,
3 + 5 * 7 % 4
evaluates to 6
.
Example 2
- Predict the result of the following expression.
- Explain how the addition of parenthesis influences the result.
- Check to see if you are correct by running it in the Java Playground.
Explanation:
- The parenthesis override the order of operations causing the first operation to be modulus division
7 % 4
, which is 3
. Leaving us with 3 + 5 * 3
.
- The next operation is multiplication
5 * 3
, which is 15
. Leavning us with 3 + 15
.
- The last operation is addition
3 + 15
, which is 18
.
- So,
3 + 5 * (7 % 4)
evaluates to 18
.
Example 3
- Predict the result of the following expression.
- Explain how the addition of parenthesis influences the result.
- Check to see if you are correct by running it in the Java Playground.
Explanation:
- The parenthesis override the order of operations causing the first operation to be additiona,
3 + 5
, which is 8
. Leaving us with 8 * 7 % 4
.
- The next operation is multiplication
8 * 7
, which is 56
. Leaving us with 56 % 4
.
- The last operation is modulus
56 % 4
. Since 56
is divisible by 4
, there is no remainder and the result is 0
.
- So,
(3 + 5) * 7 % 4
evaluates to 0
.
Example 4
- Predict the result of the following expression.
- Explain how the addition of parenthesis influences the result.
- Check to see if you are correct by running it in the Java Playground.
Explanation:
- The parenthesis override the order of operations. Working left to right, the first operation that is evaluated is
3 + 5
, which is 8
. Leaving us with 8 * (7 % 4)
.
- The next operation in parenthesis is then evaluated
7 % 4
, which is 3
. Leaving us with 8 * 3
.
- The last operation is multiplication
8 * 3
, which is 24
.
- So,
(3 + 5) * (7 % 4)
evaluates to 24
.
Resources
Next Learn Tutorial
Learn: Expressions and the Assignment Operator