Learn › Java Programming

Control Structures

Master conditional branching and looping constructs in Java including if-else, switch, for, while, and enhanced for loops.

If-Else Statements

The if-else statement is the fundamental decision-making construct in Java, directing program flow based on boolean conditions. Conditions must evaluate to a boolean value, unlike some languages that allow truthy or falsy conversions. You can chain multiple conditions with else if to handle more than two cases. The ternary operator provides a compact alternative for simple conditional assignments.

public class IfElseDemo {
    public static void main(String[] args) {
        int score = 85;

        // Basic if-else chain
        if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 80) {
            System.out.println("Grade: B");
        } else if (score >= 70) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: F");
        }

        // Ternary operator
        String result = score >= 60 ? "Pass" : "Fail";
        System.out.println(result);  // "Pass"

        // Logical operators
        int age = 25;
        boolean hasLicense = true;
        if (age >= 16 && hasLicense) {
            System.out.println("Can drive");
        }
    }
}

Switch Statements and Expressions

Switch statements allow you to select between multiple execution paths based on the value of an expression. Traditional switch statements use case labels with break to prevent fall-through. Java 14 introduced switch expressions with arrow syntax that eliminates the need for break statements and allows switch to return a value. Switch can be used with byte, short, char, int, String, and enum types.

public class SwitchDemo {
    public static void main(String[] args) {
        // Traditional switch
        String day = "WEDNESDAY";
        switch (day) {
            case "MONDAY":
            case "TUESDAY":
            case "WEDNESDAY":
            case "THURSDAY":
            case "FRIDAY":
                System.out.println("Weekday");
                break;
            case "SATURDAY":
            case "SUNDAY":
                System.out.println("Weekend");
                break;
            default:
                System.out.println("Invalid day");
        }

        // Switch expression (Java 14+)
        int numLetters = switch (day) {
            case "MONDAY", "FRIDAY", "SUNDAY" -> 6;
            case "TUESDAY" -> 7;
            case "WEDNESDAY" -> 9;
            case "THURSDAY", "SATURDAY" -> 8;
            default -> throw new IllegalArgumentException("Invalid day");
        };
        System.out.println(day + " has " + numLetters + " letters");
    }
}

For and While Loops

Java provides the traditional for loop with initialization, condition, and update expressions for counted iteration. The while loop executes a block repeatedly as long as its condition is true, and the do-while variant guarantees at least one execution. Break terminates the innermost loop entirely, while continue skips to the next iteration. Labeled break and continue statements allow you to control nested loops, though they should be used sparingly for clarity.

public class LoopDemo {
    public static void main(String[] args) {
        // Traditional for loop
        for (int i = 0; i < 5; i++) {
            System.out.print(i + " ");  // 0 1 2 3 4
        }
        System.out.println();

        // While loop
        int count = 10;
        while (count > 0) {
            System.out.print(count + " ");
            count -= 2;
        }
        System.out.println();  // 10 8 6 4 2

        // Do-while loop
        int num = 0;
        do {
            System.out.println("Executed at least once: " + num);
            num++;
        } while (num < 0);

        // Break and continue
        for (int i = 0; i < 100; i++) {
            if (i % 2 != 0) continue;  // Skip odd numbers
            if (i > 10) break;          // Stop after 10
            System.out.print(i + " ");   // 0 2 4 6 8 10
        }
        System.out.println();
    }
}

Enhanced For Loop

The enhanced for loop, also known as the for-each loop, provides a cleaner syntax for iterating over arrays and collections. It eliminates the need for index management and reduces the risk of off-by-one errors. The enhanced for loop works with any object that implements the Iterable interface. While it is simpler and less error-prone, it does not provide access to the current index, so the traditional for loop is still necessary when index-based operations are required.

import java.util.List;
import java.util.Map;

public class EnhancedForDemo {
    public static void main(String[] args) {
        // Enhanced for with array
        String[] fruits = {"apple", "banana", "cherry", "date"};
        for (String fruit : fruits) {
            System.out.println(fruit.toUpperCase());
        }

        // Enhanced for with List
        List<Integer> numbers = List.of(10, 20, 30, 40, 50);
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("Sum: " + sum);  // 150

        // Iterating over a Map
        Map<String, Integer> ages = Map.of(
            "Alice", 30,
            "Bob", 25,
            "Charlie", 35
        );
        for (Map.Entry<String, Integer> entry : ages.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

← Variables & Data Types · Methods & Overloading →