Control Structures
Control Flow
Use if/else, switch statements, and loops to control the flow of your Java programs.
if / else
The most basic control structure. Execute code based on a condition.
switch Statement
A cleaner alternative to long if/else chains when comparing one value against multiple options.
Java 14+ supports switch expressions with a cleaner arrow syntax.
Loops
for— when you know how many iterationswhile— while a condition is truedo-while— like while, but runs at least oncefor-each— iterate over collections and arrays
Example
java
// if / else
int score = 75;
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("F");
}
// switch statement
String day = "MONDAY";
switch (day) {
case "MONDAY":
case "TUESDAY":
System.out.println("Weekday");
break;
case "SATURDAY":
case "SUNDAY":
System.out.println("Weekend");
break;
default:
System.out.println("Midweek");
}
// Switch expression (Java 14+)
String result = switch (day) {
case "MONDAY", "FRIDAY" -> "Start/end";
case "SATURDAY", "SUNDAY" -> "Weekend";
default -> "Midweek";
};
// for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while loop
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
// for-each loop
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}Try it yourself — JAVA