Notifications

No notifications

/Phase 1

Control Flow & switch

Branch and Loop 🔀

Java's control flow is C-family — same keywords as C/C++/JavaScript with a couple of modern twists.

if / else if / else

int 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");

Loops

// 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 Expression

Classic 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";
};

Pattern Matching for switch (Java 21)

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";
};

On this page

Detailed Theory

if — Always Use Braces

Even 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!

Boolean Operators

&&  // logical AND, short-circuits
||  // logical OR,  short-circuits
!   // NOT
==  // equality (reference for objects, value for primitives)
!=  // inequality

&

^ // bitwise — also works on booleans (no short-circuit)

> Use && and

for control flow — they short-circuit, avoiding NPE / divide-by-zero.

if (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.

while and do-while

int 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 for Loop

for (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.

break and continue

for (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 Generations

1. 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 break and 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";
};

  • Returns a value.
  • No fallthrough.
  • Multiple labels per arm (1, 2, 3).
  • Compiler enforces exhaustiveness (every value covered).
For multi-statement branches, use a block + yield:

int rate = switch (level) {
    case "premium" -> 100;
    case "basic"   -> 50;
    case "free"    -> {
        log("free user");
        yield 0;
    }
    default        -> throw new IllegalArgumentException(level);
};

3. Pattern Matching for switch (Java 21)

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.

When to Use Each

ConstructUse case
if/elseConditions on continuous values, multiple unrelated checks
switch (expression)Mapping a discrete value to another value/string
switch (pattern)Type-dispatch over sealed hierarchy / objects
whileLoop with unknown count
do-whileLoop that must run at least once (input validation)
forCounted loop with index
Enhanced forIterate every element — clearest, fewest bugs

Common Mistakes

BugFix
Missing break in classic switchUse switch expression with ->
if (a = b) instead of a == bJava forbids non-boolean conditions, so this is a compile error for ints — but watch for boolean variables
Off-by-one on <= lengthUse < arr.length or enhanced for
Modifying a list during enhanced forUse Iterator.remove() or stream filter
Comparing strings with == in a switchswitch on Strings uses .equals() automatically — that's fine

Cheat-Sheet

NeedCode
Branchif (cond) { ... } else { ... }
Map a valuevar x = switch(k) { case A -> 1; default -> 0; };
Counted loopfor (int i = 0; i < n; i++)
Iterate elementsfor (T x : iterable)
At-least-oncedo { ... } while (cond);
Exit nested looplabelled break
Type dispatchpattern-matching switch (Java 21)

You've got branching down. Phase 2 next: methods, strings, arrays, and your first classes.