Last 30 Days
No notifications
Java's control flow is C-family — same keywords as C/C++/JavaScript with a couple of modern twists.
if / else if / elseint score = 78;
if (score >= 90) System.out.println("A");
else if (score >= 75) System.out.println("B");
else if (score >= 60) System.out.println("C");
else System.out.println("F");// while
int i = 0;
while (i < 5) { System.out.println(i++); }// do-while (runs at least once)
do { /* ... */ } while (cond);
// classic for
for (int j = 0; j < 5; j++) System.out.println(j);
// enhanced for (foreach) — works on arrays and Iterable
int[] arr = {10, 20, 30};
for (int x : arr) System.out.println(x);
switch Statement vs ExpressionClassic statement (C-style fallthrough — easy to forget break):
switch (day) {
case 1: case 2: case 3: case 4: case 5:
System.out.println("weekday"); break;
case 6: case 7:
System.out.println("weekend"); break;
default:
System.out.println("invalid");
}Modern switch expression (Java 14+) — no fallthrough, returns a value:
String label = switch (day) {
case 1, 2, 3, 4, 5 -> "weekday";
case 6, 7 -> "weekend";
default -> "invalid";
};Object obj = "hello";
String desc = switch (obj) {
case Integer i -> "int " + i;
case String s -> "string of length " + s.length();
case null -> "null";
default -> "other";
};if — Always Use BracesEven for one-liners, Java style guides recommend braces:
if (x > 0) {
System.out.println("positive");
}Skipping braces can hide bugs:
if (x > 0)
System.out.println("a");
System.out.println("b"); // ALWAYS runs — not part of the if!&& // logical AND, short-circuits || // logical OR, short-circuits ! // NOT == // equality (reference for objects, value for primitives) != // inequalityfor control flow — they short-circuit, avoiding NPE / divide-by-zero.&
^ // bitwise — also works on booleans (no short-circuit) > Use
&&andif (str != null && str.length() > 0) /* safe */; if (x != 0 && 100 / x > 1) /* safe */;Ternary
String label = (score >= 60) ? "pass" : "fail"; int max = a > b ? a : b;Don't nest ternaries deeply — they get unreadable fast.
whileanddo-whileint n = 10; while (n > 0) { System.out.println(n); n--; }int x; do { x = readUserInput(); } while (x < 0); // loop body runs at least once
Classic
forLoopfor (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }// Multiple init / update for (int i = 0, j = arr.length - 1; i < j; i++, j--) { /* ... */ }
// Infinite loop — the canonical idiom for (;;) { if (done) break; }
Enhanced
for(foreach)Works on arrays and anything implementing
Iterable:int[] arr = {1, 2, 3}; for (int x : arr) System.out.println(x);List<String> names = List.of("a", "b", "c"); for (String n : names) System.out.println(n);
Map<String, Integer> ages = Map.of("Asha", 19, "Bishan", 21); for (var entry : ages.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); }
> Foreach gives you the value, not the index. If you need the index, use a classic
for.
breakandcontinuefor (int i = 0; i < 10; i++) { if (i == 5) break; // exit the loop if (i % 2 == 0) continue; // skip to next iteration System.out.println(i); }Labeled Break (rare but useful)
outer: for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (matrix[i][j] == target) { System.out.println("found at " + i + "," + j); break outer; // break BOTH loops } } }
switch— Three Generations1. Classic Statement (1.0)
switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("weekday"); break; case 6: case 7: System.out.println("weekend"); break; default: System.out.println("invalid"); }⚠️ Forget
breakand execution falls through to the next case. This is the source of countless bugs.2. Switch Expression (Java 14)
String label = switch (day) { case 1, 2, 3, 4, 5 -> "weekday"; case 6, 7 -> "weekend"; default -> "invalid"; };
1, 2, 3).yield:int rate = switch (level) {
case "premium" -> 100;
case "basic" -> 50;
case "free" -> {
log("free user");
yield 0;
}
default -> throw new IllegalArgumentException(level);
};Type-tested with binding:
sealed interface Shape permits Circle, Square, Rect {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Rect(double w, double h) implements Shape {}double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Square sq -> sq.side() * sq.side();
case Rect r -> r.w() * r.h();
};
}
Add guards:
String describe(Object o) {
return switch (o) {
case Integer i when i < 0 -> "negative int";
case Integer i -> "int " + i;
case String s -> "string \"" + s + "\"";
case null -> "null";
default -> "other";
};
}> Pattern matching for switch only switches on what the JVM can statically know — generally objects and primitives that fit in 32 bits (int, String, enum), and reference types under sealed hierarchies.
| Construct | Use case | |||
if/else | Conditions on continuous values, multiple unrelated checks | |||
switch (expression) | Mapping a discrete value to another value/string | |||
switch (pattern) | Type-dispatch over sealed hierarchy / objects | |||
while | Loop with unknown count | |||
do-while | Loop that must run at least once (input validation) | |||
for | Counted loop with index | |||
Enhanced for | Iterate every element — clearest, fewest bugs | Common Mistakes | Bug | Fix |
Missing break in classic switch | Use switch expression with -> | |||
if (a = b) instead of a == b | Java forbids non-boolean conditions, so this is a compile error for ints — but watch for boolean variables | |||
Off-by-one on <= length | Use < arr.length or enhanced for | |||
| Modifying a list during enhanced for | Use Iterator.remove() or stream filter | |||
Comparing strings with == in a switch | switch on Strings uses .equals() automatically — that's fine | Cheat-Sheet | Need | Code |
| Branch | if (cond) { ... } else { ... } | |||
| Map a value | var x = switch(k) { case A -> 1; default -> 0; }; | |||
| Counted loop | for (int i = 0; i < n; i++) | |||
| Iterate elements | for (T x : iterable) | |||
| At-least-once | do { ... } while (cond); | |||
| Exit nested loop | labelled break | |||
| Type dispatch | pattern-matching switch (Java 21) |
You've got branching down. Phase 2 next: methods, strings, arrays, and your first classes.