Control Flow

Conditional Statements

if Statement

if (condition) {
    // executed if condition is true
}

if (x > 0) {
    System.out.println("positive");
} else {
    System.out.println("non-positive");
}

if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}

Ternary Operator

String result = (x > 0) ? "positive" : "non-positive";
int max = (a > b) ? a : b;
String status = (count == 1) ? "item" : "items";

Switch Statement

Traditional Switch

switch (day) {
    case MONDAY:
    case TUESDAY:
    case WEDNESDAY:
    case THURSDAY:
    case FRIDAY:
        System.out.println("Weekday");
        break;
    case SATURDAY:
    case SUNDAY:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Unknown");
}

Switch Expression (Arrow Syntax)

String dayType = switch (day) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
    case SATURDAY, SUNDAY -> "Weekend";
};

int numDays = switch (month) {
    case JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER -> 31;
    case APRIL, JUNE, SEPTEMBER, NOVEMBER -> 30;
    case FEBRUARY -> 28;
};

Switch with yield

String description = switch (code) {
    case 200 -> "OK";
    case 404 -> "Not Found";
    case 500 -> {
        log("Server error");
        yield "Internal Server Error";
    }
    default -> "Unknown";
};

Loops

for Loop

for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

// Multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println(i + " " + j);
}

// Infinite loop
for (;;) {
    // Use break to exit
}

Enhanced for Loop (for-each)

int[] numbers = {1, 2, 3, 4, 5};
for (int n : numbers) {
    System.out.println(n);
}

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
    System.out.println(name);
}

// Works with any Iterable
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

while Loop

int count = 0;
while (count < 10) {
    System.out.println(count);
    count++;
}

// Reading until condition
while (hasMore()) {
    process(next());
}

do-while Loop

int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 10);

// Always executes at least once
do {
    response = getInput();
} while (!isValid(response));

Loop Control

break Statement

for (int i = 0; i < 100; i++) {
    if (found(i)) {
        break;  // Exit the loop
    }
}

// Break from nested loops with label
outer:
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        if (condition) {
            break outer;  // Exit both loops
        }
    }
}

continue Statement

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    System.out.println(i);
}

// Continue with label
outer:
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        if (skip(i, j)) {
            continue outer;  // Continue outer loop
        }
    }
}

Labeled Statements

search:
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (matrix[i][j] == target) {
            found = true;
            break search;
        }
    }
}

Exception Handling

try-catch

try {
    int result = divide(a, b);
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

Multiple catch Blocks

try {
    processFile(filename);
} catch (FileNotFoundException e) {
    System.out.println("File not found: " + filename);
} catch (IOException e) {
    System.out.println("I/O error: " + e.getMessage());
} catch (Exception e) {
    System.out.println("Unexpected error: " + e.getMessage());
}

Multi-catch (Union Types)

try {
    process();
} catch (IOException | SQLException e) {
    System.out.println("Error: " + e.getMessage());
}

try-catch-finally

FileReader reader = null;
try {
    reader = new FileReader(filename);
    // process file
} catch (IOException e) {
    System.out.println("Error reading file");
} finally {
    // Always executed
    if (reader != null) {
        reader.close();
    }
}

try-with-resources

try (FileReader reader = new FileReader(filename);
     BufferedReader buffered = new BufferedReader(reader)) {
    String line;
    while ((line = buffered.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
}
// Resources automatically closed

throw Statement

public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}

public void process() throws IOException {
    throw new IOException("Processing failed");
}

throws Clause

public void readFile(String name) throws FileNotFoundException, IOException {
    FileReader reader = new FileReader(name);
    // ...
}

Assertions

assert value >= 0 : "Value must be non-negative";
assert list != null;
assert index < array.length : "Index out of bounds: " + index;
Note: Assertions are disabled by default. Enable with -ea flag.

return Statement

// Return value
public int calculate() {
    return 42;
}

// Early return
public String process(String input) {
    if (input == null) {
        return "";
    }
    return input.trim();
}

// Void return
public void check(int n) {
    if (n < 0) {
        return;  // Exit method early
    }
    process(n);
}