Operators: The Math Engine

Operators: The Math Engine in Java: Operators are the "Verbs" of Java. They are the symbols that perform math, compare values, or join logic together.

Concept Explanation

Operators are the "Verbs" of Java. They are the symbols that perform math, compare values, or join logic together.


Syntax or Core Structure

1. Arithmetic (+, -, *, /, %)

The Modulo (%) is the most interesting one — it gives you the Remainder of a division.

int remainder = 10 % 3; // 1 (Because 3 goes in 3 times with 1 left over)

2. Comparison (==, !=, >, <, >=, <=)

Note: Use == to check equality. = is only for assigning values!

3. Logical (&&, ||, !)

  • && (AND): True if BOTH sides are true.
  • || (OR): True if AT LEAST ONE side is true.
  • ! (NOT): Flips the result (!true becomes false).

Real World Example

Price Checker:

boolean isAffordable = (userBalance >= itemPrice);
boolean canBuy = isAffordable && !isItemOutOfStock;

Common Mistakes

  1. Integer Division: int x = 5 / 2; results in 2, not 2.5. Java chops off the decimal in integer math.
  2. Equality Confusion: Using if (x = 5) instead of if (x == 5). The first one will actually try to change x to 5!

Practice Exercises

  1. The Even/Odd Checker: Use the modulo (%) operator to determine if a number is even or odd.
  2. The Discount Logic: Use logical operators to decide if a customer gets a discount (must be over 65 OR have a membership card).
  3. The Incrementer: Research the difference between ++i and i++. Write a script to test both.