Applying the Order of Operations
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 is35. Leaving us with3 + 35 % 4. - The second operation is modulus division
35 % 4, which is3. Leaving us with3 + 3. - The last operation is addition
3 + 3, which is6. - So,
3 + 5 * 7 % 4evaluates to6.
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 is3. Leaving us with3 + 5 * 3. - The next operation is multiplication
5 * 3, which is15. Leavning us with3 + 15. - The last operation is addition
3 + 15, which is18. - So,
3 + 5 * (7 % 4)evaluates to18.
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 is8. Leaving us with8 * 7 % 4. - The next operation is multiplication
8 * 7, which is56. Leaving us with56 % 4. - The last operation is modulus
56 % 4. Since56is divisible by4, there is no remainder and the result is0. - So,
(3 + 5) * 7 % 4evaluates to0.
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 is8. Leaving us with8 * (7 % 4). - The next operation in parenthesis is then evaluated
7 % 4, which is3. Leaving us with8 * 3. - The last operation is multiplication
8 * 3, which is24. - So,
(3 + 5) * (7 % 4)evaluates to24.