Skip to main content
Module 1 · Lesson 2 of 32/22 in the course~14 min
Module lessons (2/3)

Flow Control and Switch

Explore Stage

Deterministic flow and zero fall-through

Govern decisions and iterations by writing modern constructs that are easy to read and impossible to misunderstand.

To react to data at runtime, Java provides strictly typed conditional structures on boolean and four loop variants.

1. Conditionals if / else if / else and Short Circuit

Unlike C/C++, in Java the condition of if (...) must have exactly type boolean:

Java
public class Main {
    public static void main(String[] args) {
        int temperature = 25;
        boolean hasTicket = true;

        if (temperature >= 20 && hasTicket) {
            System.out.println("Accesso consentito al concerto.");
        } else if (temperature < 10) {
            System.out.println("Porta una giacca.");
        } else {
            System.out.println("Ingresso standard.");
        }
    }
}

The logical operators && (AND) and || (OR) apply the short-circuit: if the left side already decides the result, the JVM does not even evaluate the right side (useful for protecting controls like name != null && name.length() > 0).

2. for, while, do-while and Enhanced for-each

Each loop has a clear use case:

Java
public class Main {
    public static void main(String[] args) {
        // 1. for classico quando serve l'indice
        for (int i = 0; i < 3; i++) {
            System.out.println("Indice: " + i);
        }

        // 2. for-each per leggere ogni elemento di un array o collezione
        String[] tags = { "java", "jvm", "backend" };
        for (String tag : tags) {
            System.out.println(tag);
        }

        // 3. while guidato da una condizione dinamica
        int attempts = 3;
        while (attempts > 0) {
            attempts--;
        }
    }
}

3. Control with break, continue and Labeled Loops

continue skip to the next iteration; break immediately exits the current loop:

Java
for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue; // Salta la stampa di 3
    }
    if (i == 5) {
        break;    // Interrompe prima di stampare 5
    }
    System.out.println(i); // Stampa 1, 2, 4
}

4. switch Classic vs Switch Expression (Java 14+)

The traditional switch with colon (case 1:) continues into subsequent branches if you forget break; (fall-through). Since Java 14+, the switch expression with -> eliminates fall-through and can directly return a value:

Java
int day = 3;

String badge = switch (day) {
    case 1, 2, 3, 4, 5 -> "Giorno lavorativo";
    case 6, 7 -> "Weekend";
    default -> {
        yield "Giorno non valido";
    }
};
System.out.println(badge);

Try it yourself

Exercise#java.m1.l2.e1
Attempts: 0Loading…

Complete the code by checking score: if score >= 60 prints "Pass", otherwise prints "Fail".

Loading editor…
Show hint

Use if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }.

Solution available after 3 attempts

Exercise#java.m1.l2.e2
Attempts: 0Loading…

Write a for loop that prints the integers 1 to 5 (inclusive) on separate lines.

Loading editor…
Show hint

Use for (int i = 1; i <= 5; i++) { System.out.println(i); }.

Solution available after 3 attempts

Exercise#java.m1.l2.e3
Attempts: 0Loading…

Complete the while loop to print the numbers 3 to 1 (inclusive) in descending order using count.

Loading editor…
Show hint

Write while (count >= 1) by printing count and decrementing it with count--;.

Solution available after 3 attempts

Quiz#java.m1.l2.e4
Ready

Which string prints this classic switch with code = 2?

Java
int code = 2;
switch (code) {
    case 1: System.out.print("A");
    case 2: System.out.print("B");
    case 3: System.out.print("C"); break;
    default: System.out.print("D");
}
Answer options
Quiz#java.m1.l2.e5
Ready

What is printed at the end of this loop with continue?

Java
int sum = 0;
for (int i = 1; i <= 4; i++) {
    if (i % 2 == 0) continue;
    sum += i;
}
System.out.println(sum);
Answer options