Module lessons (2/3)
Flow Control and Switch
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:
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:
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:
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:
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
Complete the code by checking score: if score >= 60 prints "Pass", otherwise prints "Fail".
Show hint
Use if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }.
Solution available after 3 attempts
Write a for loop that prints the integers 1 to 5 (inclusive) on separate lines.
Show hint
Use for (int i = 1; i <= 5; i++) { System.out.println(i); }.
Solution available after 3 attempts
Complete the while loop to print the numbers 3 to 1 (inclusive) in descending order using count.
Show hint
Write while (count >= 1) by printing count and decrementing it with count--;.
Solution available after 3 attempts
Which string prints this classic switch with code = 2?
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");
}What is printed at the end of this loop with continue?
int sum = 0;
for (int i = 1; i <= 4; i++) {
if (i % 2 == 0) continue;
sum += i;
}
System.out.println(sum);