Jan 24, 2026
## Chapter 6: The Math and Logic (Operators)
Operators are just symbols that tell Java to do something with your variables.
### The Math Operators (`+`, `-`, `*`, `/`, `%`)
Most are simple, but `/` and `%` cause the most tears in my class.
- **`/` (Division)**: If you divide two integers, Java gives you an integer. `10 / 3` is `3`, not `3.33`.
- **`%` (Modulo)**: This gives you the *remainder*. `10 % 3` is `1` (because 3 goes into 10 three times, and 1 is left over).
### The Shortcut Operators (`++`, `--`)
- `x++` means "Use the value first, then add 1".
- `++x` means "Add 1 first, then use the value".
### Examples for Chapter 6:
**1. Basic (The Modulo trick):**
```java
int n = 15;
System.out.println(n % 2); // Result: 1
```
*Teacher's comment:* This is the easiest way to check if a number is Even or Odd. If `n % 2 == 0`, it's even. If it's `1`, it's odd.
**2. Common Mistake (The "Integer Division" trap):**
```java
double result = 10 / 4;
System.out.println(result); // Result: 2.0 (NOT 2.5!)
```
*Why this happens:* Java sees `10` and `4` as integers. It does the math first (`10 / 4 = 2`) and *then* converts it to a double (`2.0`).
*Fix:* Write it as `10.0 / 4` or `10 / 4.0`.
**3. Explanation-Focused (Short-Circuit Logic):**
Look at the `&&` (AND) and `||` (OR) operators.
```java
if (isUserLoggedIn && hasPremiumAccess) { ... }
```
If `isUserLoggedIn` is `false`, Java doesn't even look at `hasPremiumAccess`. It stops immediately.
*Why:* Because for an `&&` to be true, both must be true. If the first is false, the whole thing is already false. This saves time and prevents crashes!
**4. Real-Life (The "Equal" problem):**
```java
String s1 = "hello";
String s2 = new Scanner(System.in).nextLine(); // user types "hello"
System.out.println(s1 == s2); // FALSE!
```
*Teacher's comment:* Never use `==` for Strings. It checks if they are the "same box" (address). Use `.equals()` to check if the "text inside" is the same. This is the #1 mistake students make in their first month.
**5. Advanced Hint (The Ternary Operator):**
Instead of a long `if-else`, you can write:
```java
String msg = (marks >= 40) ? "Pass" : "Fail";
```
It's a "Short-hand If". It means: "If marks >= 40, give me 'Pass', otherwise give me 'Fail'". Use it sparingly; don't make your code hard to read!