5. Branching Structures

Branching statements alter the flow of execution by jumping to another part of the program.

break Statement

Exits a loop or switch statement immediately.

Example:

public class BreakExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {

            if (i == 5) {

                break; // Exits loop when i is 5

            }

            System.out.println("i: " + i);

        }

        // Output:

        // i: 1

        // i: 2

        // i: 3

        // i: 4

    }

}

Notes:

Can be used in for, while, do-while, or switch.

Labeled break: Breaks out of a specific outer loop (rarely used).

outer: for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 3; j++) {

        if (i == 2 && j == 2) {

            break outer; // Exits both loops

        }

    }

}