๐Ÿ“˜ Order of Operations

PEMDAS vs. Java Operator Precedence

๐ŸŽฏ Why This Matters

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.

๐Ÿ”ข Part 1: PEMDAS (What You Learned in Math)

PEMDAS tells us the order to solve math expressions:

  1. P โ€“ Parentheses ( )
  2. E โ€“ Exponents
  3. M โ€“ Multiplication
  4. D โ€“ Division
  5. A โ€“ Addition
  6. S โ€“ Subtraction

Important:

โœ๏ธ Example

8 + 4 ร— 2

Steps:

โœ… Answer: 16

๐Ÿ’ป Part 2: Java Order of Operations (Operator Precedence)

Java follows rules similar to PEMDAS, but with more operators. This is called operator precedence.

๐Ÿ” Common Java Operator Precedence (High โ†’ Low)

  1. Parentheses ( )
  2. Unary operators ++ -- + - !
  3. Multiplication / Division / Modulus * / %
  4. Addition / Subtraction + -
  5. Relational operators < > <= >=
  6. Equality operators == !=
  7. Logical AND &&
  8. Logical OR ||
  9. Assignment =

Note: Java has more operators than this list, but these are the ones youโ€™ll use most often.

๐Ÿง  Key Difference: Java is NOT Just Math

Java evaluates expressions using precedence rules, one step at a time.

Example 1

int result = 10 + 6 / 2;

Steps:

โœ… result = 13

Example 2 (Using Parentheses)

int result = (10 + 6) / 2;

Steps:

โœ… result = 8

โš ๏ธ Modulus (%) in Java

Java includes modulus, which finds the remainder.

int x = 10 % 3;

โœ… x = 1

โš ๏ธ Integer Division Gotcha

If both numbers are integers, Java cuts off decimals. (This is called integer division.)

int x = 5 / 2;

โœ… x = 2

To fix:

double x = 5.0 / 2;

โœ… x = 2.5

๐Ÿ”„ Left-to-Right Rule Still Applies

When operators have the same precedence, Java evaluates left to right.

int x = 20 / 5 * 2;

Steps:

โœ… x = 8

๐Ÿงฉ Comparison Example (Very Common Bug)

boolean answer = 10 > 5 + 3;

Steps:

โœ… answer = true

โญ Best Practice Rule

When in doubt, use parentheses.

๐Ÿ“ Quick Summary

Concept Math (PEMDAS) Java
Parentheses โœ” โœ”
Multiplication / Division โœ” โœ”
Addition / Subtraction โœ” โœ”
Modulus (%) โŒ โœ”
Logical operators โŒ โœ”
Integer division โŒ โœ”

๐Ÿงช Practice Check

What is the output?

System.out.println(8 + 12 / 4 * 2);

Steps:

โœ… Output: 14