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 (
!truebecomesfalse).
Real World Example
Price Checker:
boolean isAffordable = (userBalance >= itemPrice);
boolean canBuy = isAffordable && !isItemOutOfStock;
Common Mistakes
- Integer Division:
int x = 5 / 2;results in2, not2.5. Java chops off the decimal in integer math. - Equality Confusion: Using
if (x = 5)instead ofif (x == 5). The first one will actually try to changexto 5!
Practice Exercises
- The Even/Odd Checker: Use the modulo (
%) operator to determine if a number is even or odd. - The Discount Logic: Use logical operators to decide if a customer gets a discount (must be over 65 OR have a membership card).
- The Incrementer: Research the difference between
++iandi++. Write a script to test both.