ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Java Tutorial• 6 min read

Control Flow, Enhanced Switch & Loops

if-else, modern switch expressions with yield, for-each loops

Java provides standard branching (if-else) and looping (for, while, enhanced for-each) constructs, plus modern arrow switch expressions in Java 14+.

Modern Switch Expressions & For-Each

Enhanced Switch (->): Returns values directly, eliminates fallthrough bugs, and does not require manual break statements.

For-Each Loop (for (Type item : collection)): Cleanly iterates arrays and collections without managing index bounds.

Enhanced Switch Expression & For-Each
public class SwitchDemo {
    public static void main(String[] args) {
        int day = 3;
        String dayName = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4, 5 -> "Weekday";
            default -> "Weekend";
        };
        System.out.println("Day: " + dayName);

        int[] grades = {88, 92, 79, 95};
        for (int grade : grades) {
            System.out.println("Grade: " + grade);
        }
    }
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

In modern Java enhanced switch statements (`case 1 -> ...`), is a manual `break;` statement required to prevent fallthrough?