JaJava · Lesson 3 of 9
Control Flow
Java control flow is straight C-family. No surprises, no weird tricks. The enhanced switch expression in Java 14+ is genuinely nice.
Java
public class ControlFlow {
public static void main(String[] args) {
int score = 85;
if (score >= 90) System.out.println("A");
else if (score >= 80) System.out.println("B");
else if (score >= 70) System.out.println("C");
else System.out.println("Below C");
// Ternary
String result = score >= 60 ? "Pass" : "Fail";
// Enhanced switch expression (Java 14+)
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
System.out.println(dayName); // Wednesday
// Classic switch (still valid)
String quarter = switch (day) {
case 1: case 2: case 3:
yield "Q1";
case 4: case 5: case 6:
yield "Q2";
default:
yield "Later";
};
System.out.println(result);
}
}Java
import java.util.List;
public class Loops {
public static void main(String[] args) {
// for loop
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}
System.out.println();
// Enhanced for (for-each)
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// List with for-each
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
for (int n : numbers) {
System.out.print(n * n + " "); // 1 4 9 16 25
}
System.out.println();
// while
int n = 10;
while (n > 0) {
System.out.print(n + " ");
n -= 3;
}
System.out.println();
// do-while — runs at least once
int count = 0;
do {
count++;
} while (count < 5);
System.out.println("count: " + count); // 5
// Labels for nested loop control
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) break outer; // break outer loop
System.out.print("(" + i + "," + j + ") ");
}
}
}
}