JvJava

Java: Control flow – code examples

Contents

if / else if / else

Control flow#if#conditionCompare in all languages
Use case: React differently, e.g. compute grades or price tiers.
public class Main {
    public static void main(String[] args) {
        int punkte = 73;
        if (punkte >= 90) {
            System.out.println("very good");
        } else if (punkte >= 70) {
            System.out.println("good");
        } else {
            System.out.println("needs improvement");
        }
    }
}

The condition goes in parentheses and must be a boolean; blocks are formed with curly braces.

for loops

Control flow#for#loop#foreachCompare in all languages
Use case: Process every element of a collection or repeat n times.
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println("Round " + i);
        }
        for (String frucht : new String[]{"Apple", "Pear"}) {
            System.out.println(frucht);
        }
    }
}

The first loop is the classic counting loop (0, 1, 2), the second is the for-each loop over an array.

switch expression

Control flow#switch#expression#arrow
Use case: Map values by case (weekdays, status codes, price tiers).
public class Main {
    static String tagesart(int tag) {
        return switch (tag) {
            case 6, 7 -> "Weekend";
            case 1, 2, 3, 4, 5 -> "Weekday";
            default -> throw new IllegalArgumentException("Invalid: " + tag);
        };
    }
    public static void main(String[] args) {
        System.out.println(tagesart(3));
        System.out.println(tagesart(7));
    }
}

A switch expression returns a value directly; no break, no fall-through. Output: Weekday, Weekend.