Operators & Control Flow
Arithmetic, comparison and logical operators, if/else, switch expressions, and for/while loops in Java.
Operators
int a = 10, b = 3;
System.out.println(a + b); // 13 addition
System.out.println(a - b); // 7 subtraction
System.out.println(a * b); // 30 multiplication
System.out.println(a / b); // 3 integer division (truncates!)
System.out.println(a % b); // 1 remainder
System.out.println(a > b); // true
System.out.println(a == b); // false
System.out.println(a != b); // true
boolean x = true, y = false;
System.out.println(x && y); // false — logical AND
System.out.println(x || y); // true — logical OR
System.out.println(!x); // false — logical NOT
Compound assignment shortcuts:
int total = 0;
total += 5; // total = total + 5
total -= 2; // total = total - 2
total++; // increment by 1
total--; // decrement by 1
if / else
int score = 82;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 75) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
Switch expressions (modern Java)
Java 14+ supports the arrow-style switch expression, which is safer than the old fall-through switch statement — no break needed, and it can return a value directly:
int day = 3;
String name = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Unknown";
};
System.out.println(name); // Weekday
Loops
// for — when you know how many iterations
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
// while — condition checked before each iteration
int n = 5;
while (n > 0) {
System.out.println(n);
n--;
}
// do-while — body always runs at least once
int attempts = 0;
do {
attempts++;
} while (attempts < 3);
// enhanced for-each — iterating a collection or array
int[] scores = {90, 85, 77};
for (int s : scores) {
System.out.println(s);
}
break exits a loop entirely; continue skips to the next iteration.
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // skip 3
if (i == 6) break; // stop at 6
System.out.println(i);
}
// prints: 0 1 2 4 5
Common mistakes
- Using
=(assignment) instead of==(comparison) inside anif— Java's compiler thankfully rejects this for non-boolean expressions. - Forgetting the old-style
switchstatement falls through withoutbreak— prefer the modern arrow syntax (->), which never falls through. - Off-by-one errors in
forloops — double-check<vs<=.
Interview questions
Q: Why does the classic Java switch statement need break?
Historically, switch falls through to the next case unless a break stops execution — inherited from C. The modern arrow-form switch (Java 14+) removes this footgun by never falling through.
Q: What's the difference between while and do-while?
while checks the condition before running the loop body, so it may run zero times. do-while checks after, so the body always runs at least once.