You're scanning a list of 10,000 products for item #4521. Once found, why keep searching? break lets you exit immediately. Or you're processing orders but want to skip cancelled ones - continue jumps to the next iteration.

Find first match (break)

Stop searching once you find what you're looking for.

target
Break.java
Replay: real traced execution (multi-file project)
public class Break {
    public static void main(String[] args) {
        int[] numbers = {10, 25, 30, 42, 55, 60};
        int target = 42;

        int foundIndex = -1;
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Checking index " + i + ": " + numbers[i]);
            if (numbers[i] == target) {
                foundIndex = i;
                break;
            }
        }

        if (foundIndex != -1) {
            System.out.println("Found " + target + " at index " + foundIndex);
        } else {
            System.out.println(target + " not found");
        }

        // Without break, would check all elements unnecessarily
        // With break, stops at first match

    }
}
public class Break {
    public static void main(String[] args) {
        int[] numbers = {10, 25, 30, 42, 55, 60};
        int target = 30;

        int foundIndex = -1;
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Checking index " + i + ": " + numbers[i]);
            if (numbers[i] == target) {
                foundIndex = i;
                break;
            }
        }

        if (foundIndex != -1) {
            System.out.println("Found " + target + " at index " + foundIndex);
        } else {
            System.out.println(target + " not found");
        }

        // Without break, would check all elements unnecessarily
        // With break, stops at first match

    }
}
public class Break {
    public static void main(String[] args) {
        int[] numbers = {10, 25, 30, 42, 55, 60};
        int target = 99;

        int foundIndex = -1;
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Checking index " + i + ": " + numbers[i]);
            if (numbers[i] == target) {
                foundIndex = i;
                break;
            }
        }

        if (foundIndex != -1) {
            System.out.println("Found " + target + " at index " + foundIndex);
        } else {
            System.out.println(target + " not found");
        }

        // Without break, would check all elements unnecessarily
        // With break, stops at first match

    }
}
  1. target ← 42, foundIndex ← -1

    1public class Break {2    public static void main(String[] args) {3        int[] numbers = {10, 25, 30, 42, 55, 60};4        int target→ 42 = 42;  //@target=30, 995        6        int foundIndex→ -1 = -1;7        for (int i = 0; i < numbers.length; i++) {
  2. for (int i = 0; i < numbers.length; i++)

    pass 1 of 4
    6int foundIndex = -1;7for (int i0 = 0; i < numbers.length6; i++) {8    System.out.println("Checking index " + i0 + ": " + numbers[i]10);9    if (numbers[i] == target) {
    outputChecking index 0: 10
    All 4 passes — pass 1 is the card above
    passinumbers[i]targetfoundIndex
    1010
    2125
    3230
    4342423
  3. foundIndex ← 3

    8System.out.println("Checking index " + i + ": " + numbers[i]);9if (numbers[i]42 == target42) {10    foundIndex→ 3 = i3;11    break;  //#?break_exit12}
  4. if (foundIndex != -1)

    15if (foundIndex3 != -1) {16    System.out.println("Found " + target42 + " at index " + foundIndex3);17} else {
    outputFound 42 at index 3
  1. target ← 30, foundIndex ← -1

    1public class Break {2    public static void main(String[] args) {3        int[] numbers = {10, 25, 30, 42, 55, 60};4        int target→ 30 = 30;5        6        int foundIndex→ -1 = -1;7        for (int i = 0; i < numbers.length; i++) {
  2. for (int i = 0; i < numbers.length; i++)

    pass 1 of 3
    6int foundIndex = -1;7for (int i0 = 0; i < numbers.length6; i++) {8    System.out.println("Checking index " + i0 + ": " + numbers[i]10);9    if (numbers[i] == target) {
    outputChecking index 0: 10
    All 3 passes — pass 1 is the card above
    passinumbers[i]targetfoundIndex
    1010
    2125
    3230302
  3. foundIndex ← 2

    8System.out.println("Checking index " + i + ": " + numbers[i]);9if (numbers[i]30 == target30) {10    foundIndex→ 2 = i2;11    break;12}
  4. if (foundIndex != -1)

    15if (foundIndex2 != -1) {16    System.out.println("Found " + target30 + " at index " + foundIndex2);17} else {
    outputFound 30 at index 2
  1. target ← 99, foundIndex ← -1

    1public class Break {2    public static void main(String[] args) {3        int[] numbers = {10, 25, 30, 42, 55, 60};4        int target→ 99 = 99;5        6        int foundIndex→ -1 = -1;7        for (int i = 0; i < numbers.length; i++) {
  2. for (int i = 0; i < numbers.length; i++)

    pass 1 of 6
    6int foundIndex = -1;7for (int i0 = 0; i < numbers.length6; i++) {8    System.out.println("Checking index " + i0 + ": " + numbers[i]10);9    if (numbers[i] == target) {
    outputChecking index 0: 10
    All 6 passes — pass 1 is the card above
    passinumbers[i]target
    1010
    2125
    3230
    4342
    5455
    656099
  3. else

    16    System.out.println("Found " + target + " at index " + foundIndex);17} else {18    System.out.println(target99 + " not found");19}
    output99 not found

break exits the innermost loop immediately. More efficient than checking all.

break Exit the innermost loop immediately. Loop terminates.

Skip invalid entries (continue)

Skip items that don't meet criteria without stopping the loop.

Continue.java
Replay: real traced execution (multi-file project)
public class Continue {
    public static void main(String[] args) {
        int[] scores = {85, -1, 92, 0, 78, -5, 95};  // -1 and -5 are invalid

        int sum = 0;
        int count = 0;

        System.out.println("Processing scores:");
        for (int score : scores) {
            if (score < 0) {
                System.out.println("  Skipping invalid: " + score);
                continue;
            }
            System.out.println("  Adding: " + score);
            sum += score;
            count++;
        }

        System.out.println("Valid scores: " + count);
        System.out.println("Sum: " + sum);
        if (count > 0) {
            System.out.println("Average: " + (sum / count));
        }

    }
}
  1. sum ← 0, count ← 0

    1public class Continue {2    public static void main(String[] args) {3        int[] scores = {85, -1, 92, 0, 78, -5, 95};  // -1 and -5 are invalid4        5        int sum→ 0 = 0;6        int count→ 0 = 0;7        8        System.out.println("Processing scores:");9        for (int score : scores) {
    outputProcessing scores:
  2. sum ← 85, count ← 1

    pass 1 of 7
    8System.out.println("Processing scores:");9for (int score85 : scores) {10    if (score < 0) {  //#?skip_invalid11        System.out.println("  Skipping invalid: " + score);12        continue;13    }14    System.out.println("  Adding: " + score85);15    sum→ 85 += score85;16    count→ 1++;17}
    output  Adding: 85
    All 7 passes — pass 1 is the card above
    passscoresumcount
    1850 850 1
    2-1
    39285 1771 2
    401772 3
    578177 2553 4
    6-5
    795255 3504 5
  3. if (score < 0)

    pass 1 of 2
    9for (int score : scores) {10    if (score-1 < 0) {  //#?skip_invalid11        System.out.println("  Skipping invalid: " + score-1);12        continue;13    }
    output  Skipping invalid: -1
  4. if (score < 0)

    pass 2 of 2
    9for (int score : scores) {10    if (score-5 < 0) {  //#?skip_invalid11        System.out.println("  Skipping invalid: " + score-5);12        continue;13    }
    output  Skipping invalid: -5
  5. System.out.println("Valid scores: " + count);

    19System.out.println("Valid scores: " + count5);20System.out.println("Sum: " + sum350);21if (count > 0) {
    outputValid scores: 5
    Sum: 350
  6. if (count > 0)

    20System.out.println("Sum: " + sum);21if (count5 > 0) {22    System.out.println("Average: " + (sum350 / count5));23}
    outputAverage: 70

continue jumps to the next iteration, skipping the rest of the loop body.

continue Skip rest of current iteration, go to next iteration.

Early exit on error

Stop processing if something goes wrong.

commands
EarlyExit.java
Replay: real traced execution (multi-file project)
public class EarlyExit {
    public static void main(String[] args) {
        String[] commands = {"load", "process", "error", "save", "exit"};

        boolean success = true;

        for (String cmd : commands) {
            System.out.println("Executing: " + cmd);

            // Stop on error
            if (cmd.equals("error")) {
                System.out.println("ERROR: Operation failed!");
                success = false;
                break;
            }

            System.out.println("  Done.");
        }

        if (success) {
            System.out.println("All commands completed successfully.");
        } else {
            System.out.println("Processing stopped due to error.");
        }
    }
}
public class EarlyExit {
    public static void main(String[] args) {
        String[] commands = {"init", "run", "complete"};

        boolean success = true;

        for (String cmd : commands) {
            System.out.println("Executing: " + cmd);

            // Stop on error
            if (cmd.equals("error")) {
                System.out.println("ERROR: Operation failed!");
                success = false;
                break;
            }

            System.out.println("  Done.");
        }

        if (success) {
            System.out.println("All commands completed successfully.");
        } else {
            System.out.println("Processing stopped due to error.");
        }
    }
}
public class EarlyExit {
    public static void main(String[] args) {
        String[] commands = {"start", "stop"};

        boolean success = true;

        for (String cmd : commands) {
            System.out.println("Executing: " + cmd);

            // Stop on error
            if (cmd.equals("error")) {
                System.out.println("ERROR: Operation failed!");
                success = false;
                break;
            }

            System.out.println("  Done.");
        }

        if (success) {
            System.out.println("All commands completed successfully.");
        } else {
            System.out.println("Processing stopped due to error.");
        }
    }
}
  1. success ← true

    1public class EarlyExit {2    public static void main(String[] args) {3        String[] commands = {"load", "process", "error", "save", "exit"};4        //@commands={"init", "run", "complete"}, {"start", "stop"}5        6        boolean success→ true = true;
  2. for (String cmd : commands)

    pass 1 of 3
    8for (String cmdload : commands) {9    System.out.println("Executing: " + cmdload);10    11    // Stop on error12    if (cmd.equals("error")) {13        System.out.println("ERROR: Operation failed!");14        success = false;15        break;16    }17    18    System.out.println("  Done.");19}
    outputExecuting: load
      Done.
    All 3 passes — pass 1 is the card above
    passcmdsuccess
    1load
    2process
    3errorfalse
  3. success ← false

    11// Stop on error12if (cmd.equals("error")) {13    System.out.println("ERROR: Operation failed!");14    success→ false = false;15    break;16}
    outputERROR: Operation failed!
  4. else

    22    System.out.println("All commands completed successfully.");23} else {24    System.out.println("Processing stopped due to error.");25}
    outputProcessing stopped due to error.
  1. success ← true

    1public class EarlyExit {2    public static void main(String[] args) {3        String[] commands = {"init", "run", "complete"};4        5        boolean success→ true = true;
  2. for (String cmd : commands)

    pass 1 of 3
    7for (String cmdinit : commands) {8    System.out.println("Executing: " + cmdinit);9    10    // Stop on error11    if (cmd.equals("error")) {12        System.out.println("ERROR: Operation failed!");13        success = false;14        break;15    }16    17    System.out.println("  Done.");18}
    outputExecuting: init
      Done.
    All 3 passes — pass 1 is the card above
    passcmdsuccess
    1init
    2run
    3completetrue
  3. if (success)

    20if (successtrue) {21    System.out.println("All commands completed successfully.");22} else {
    outputAll commands completed successfully.
  1. success ← true

    1public class EarlyExit {2    public static void main(String[] args) {3        String[] commands = {"start", "stop"};4        5        boolean success→ true = true;
  2. for (String cmd : commands)

    pass 1 of 2
    7for (String cmdstart : commands) {8    System.out.println("Executing: " + cmdstart);9    10    // Stop on error11    if (cmd.equals("error")) {12        System.out.println("ERROR: Operation failed!");13        success = false;14        break;15    }16    17    System.out.println("  Done.");18}
    outputExecuting: start
      Done.
  3. for (String cmd : commands)

    pass 2 of 2
    7for (String cmdstop : commands) {8    System.out.println("Executing: " + cmdstop);9    10    // Stop on error11    if (cmd.equals("error")) {12        System.out.println("ERROR: Operation failed!");13        success = false;14        break;15    }16    17    System.out.println("  Done.");18}
    outputExecuting: stop
      Done.
  4. if (success)

    20if (successtrue) {21    System.out.println("All commands completed successfully.");22} else {
    outputAll commands completed successfully.

Validate early and break if invalid - cleaner than deep nesting.

Process until sentinel

Process data until you encounter a special "stop" value.

data
Sentinel.java
Replay: real traced execution (multi-file project)
public class Sentinel {
    public static void main(String[] args) {
        // Data with sentinel value -1 marking end
        int[] data = {10, 20, 30, 40, -1, 50, 60};

        System.out.println("Processing until sentinel (-1):");
        int sum = 0;

        for (int value : data) {
            if (value == -1) {
                System.out.println("Sentinel found, stopping.");
                break;
            }
            System.out.println("Processing: " + value);
            sum += value;
        }

        System.out.println("Sum of processed values: " + sum);

        // Alternative: while loop
        System.out.println("\nUsing while loop:");
        int i = 0;
        int sum2 = 0;
        while (i < data.length && data[i] != -1) {
            sum2 += data[i];
            i++;
        }
        System.out.println("Sum: " + sum2);

    }
}
public class Sentinel {
    public static void main(String[] args) {
        // Data with sentinel value -1 marking end
        int[] data = {5, 10, 15, -1, 20};

        System.out.println("Processing until sentinel (-1):");
        int sum = 0;

        for (int value : data) {
            if (value == -1) {
                System.out.println("Sentinel found, stopping.");
                break;
            }
            System.out.println("Processing: " + value);
            sum += value;
        }

        System.out.println("Sum of processed values: " + sum);

        // Alternative: while loop
        System.out.println("\nUsing while loop:");
        int i = 0;
        int sum2 = 0;
        while (i < data.length && data[i] != -1) {
            sum2 += data[i];
            i++;
        }
        System.out.println("Sum: " + sum2);

    }
}
public class Sentinel {
    public static void main(String[] args) {
        // Data with sentinel value -1 marking end
        int[] data = {100, 200, 300, 400};

        System.out.println("Processing until sentinel (-1):");
        int sum = 0;

        for (int value : data) {
            if (value == -1) {
                System.out.println("Sentinel found, stopping.");
                break;
            }
            System.out.println("Processing: " + value);
            sum += value;
        }

        System.out.println("Sum of processed values: " + sum);

        // Alternative: while loop
        System.out.println("\nUsing while loop:");
        int i = 0;
        int sum2 = 0;
        while (i < data.length && data[i] != -1) {
            sum2 += data[i];
            i++;
        }
        System.out.println("Sum: " + sum2);

    }
}
  1. sum ← 0

    1public class Sentinel {2    public static void main(String[] args) {3        // Data with sentinel value -1 marking end4        int[] data = {10, 20, 30, 40, -1, 50, 60};5        //@data={5, 10, 15, -1, 20}, {100, 200, 300, 400}6        7        System.out.println("Processing until sentinel (-1):");8        int sum→ 0 = 0;
    outputProcessing until sentinel (-1):
  2. sum ← 10

    pass 1 of 5
    10for (int value10 : data) {11    if (value == -1) {  //#?sentinel_check12        System.out.println("Sentinel found, stopping.");13        break;14    }15    System.out.println("Processing: " + value10);16    sum→ 10 += value10;17}
    outputProcessing: 10
    All 5 passes — pass 1 is the card above
    passvaluesum
    1100 10
    22010 30
    33030 60
    44060 100
    5-1
  3. if (value == -1)

    10for (int value : data) {11    if (value-1 == -1) {  //#?sentinel_check12        System.out.println("Sentinel found, stopping.");13        break;14    }
    outputSentinel found, stopping.
  4. i ← 0, sum2 ← 0

    19System.out.println("Sum of processed values: " + sum100);2021// Alternative: while loop22System.out.println("\nUsing while loop:");23int i→ 0 = 0;24int sum2→ 0 = 0;25while (i < data.length && data[i] != -1) {
    outputSum of processed values: 100
    
    Using while loop:
  5. sum2 ← 10, i ← 1

    pass 1 of 4
    24int sum2 = 0;25while (i0 < data.length7 && data[i]10 != -1) {26    sum2→ 10 += data[i]10;27    i→ 1++;28}
    All 4 passes — pass 1 is the card above
    passdata[i]sum2i
    1100 100 1
    22010 301 2
    33030 602 3
    44060 1003 4
  6. System.out.println("Sum: " + sum2);

    28}29System.out.println("Sum: " + sum2100);
    outputSum: 100
  1. sum ← 0

    1public class Sentinel {2    public static void main(String[] args) {3        // Data with sentinel value -1 marking end4        int[] data = {5, 10, 15, -1, 20};5        6        System.out.println("Processing until sentinel (-1):");7        int sum→ 0 = 0;
    outputProcessing until sentinel (-1):
  2. sum ← 5

    pass 1 of 4
    9for (int value5 : data) {10    if (value == -1) {11        System.out.println("Sentinel found, stopping.");12        break;13    }14    System.out.println("Processing: " + value5);15    sum→ 5 += value5;16}
    outputProcessing: 5
    All 4 passes — pass 1 is the card above
    passvaluesum
    150 5
    2105 15
    31515 30
    4-1
  3. if (value == -1)

    9for (int value : data) {10    if (value-1 == -1) {11        System.out.println("Sentinel found, stopping.");12        break;13    }
    outputSentinel found, stopping.
  4. i ← 0, sum2 ← 0

    18System.out.println("Sum of processed values: " + sum30);1920// Alternative: while loop21System.out.println("\nUsing while loop:");22int i→ 0 = 0;23int sum2→ 0 = 0;24while (i < data.length && data[i] != -1) {
    outputSum of processed values: 30
    
    Using while loop:
  5. sum2 ← 5, i ← 1

    pass 1 of 3
    23int sum2 = 0;24while (i0 < data.length5 && data[i]5 != -1) {25    sum2→ 5 += data[i]5;26    i→ 1++;27}
    All 3 passes — pass 1 is the card above
    passdata[i]sum2i
    150 50 1
    2105 151 2
    31515 302 3
  6. System.out.println("Sum: " + sum2);

    27}28System.out.println("Sum: " + sum230);
    outputSum: 30
  1. sum ← 0

    1public class Sentinel {2    public static void main(String[] args) {3        // Data with sentinel value -1 marking end4        int[] data = {100, 200, 300, 400};5        6        System.out.println("Processing until sentinel (-1):");7        int sum→ 0 = 0;
    outputProcessing until sentinel (-1):
  2. sum ← 100

    pass 1 of 4
    9for (int value100 : data) {10    if (value == -1) {11        System.out.println("Sentinel found, stopping.");12        break;13    }14    System.out.println("Processing: " + value100);15    sum→ 100 += value100;16}
    outputProcessing: 100
    All 4 passes — pass 1 is the card above
    passvaluesum
    11000 100
    2200100 300
    3300300 600
    4400600 1000
  3. i ← 0, sum2 ← 0

    18System.out.println("Sum of processed values: " + sum1000);1920// Alternative: while loop21System.out.println("\nUsing while loop:");22int i→ 0 = 0;23int sum2→ 0 = 0;24while (i < data.length && data[i] != -1) {
    outputSum of processed values: 1000
    
    Using while loop:
  4. sum2 ← 100, i ← 1

    pass 1 of 4
    23int sum2 = 0;24while (i0 < data.length4 && data[i]100 != -1) {25    sum2→ 100 += data[i]100;26    i→ 1++;27}
    All 4 passes — pass 1 is the card above
    passdata[i]sum2i
    11000 1000 1
    2200100 3001 2
    3300300 6002 3
    4400600 10003 4
  5. System.out.println("Sum: " + sum2);

    27}28System.out.println("Sum: " + sum21000);
    outputSum: 1000

Sentinel values signal "end of data" - common in file and stream processing.

sentinel Special value marking end of data: -1, null, "END", etc.

Labeled break (nested loops)

Break out of outer loops using labels (Java-specific).

target
LabeledBreak.java
Replay: real traced execution (multi-file project)
public class LabeledBreak {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int target = 5;

        int foundRow = -1;
        int foundCol = -1;

        // Without label: only breaks inner loop
        System.out.println("Search without label (broken):");
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break;  // Only breaks inner loop!
                }
            }
            System.out.println("Still in outer loop, row " + row);
        }

        // With label: breaks outer loop
        System.out.println("\nSearch with label (correct):");
        foundRow = -1;
        foundCol = -1;

        search:
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break search;  // Breaks outer loop!
                }
            }
        }

        if (foundRow != -1) {
            System.out.println("Found " + target + " at [" + foundRow + "][" + foundCol + "]");
        } else {
            System.out.println(target + " not found");
        }

    }
}
public class LabeledBreak {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int target = 1;

        int foundRow = -1;
        int foundCol = -1;

        // Without label: only breaks inner loop
        System.out.println("Search without label (broken):");
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break;  // Only breaks inner loop!
                }
            }
            System.out.println("Still in outer loop, row " + row);
        }

        // With label: breaks outer loop
        System.out.println("\nSearch with label (correct):");
        foundRow = -1;
        foundCol = -1;

        search:
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break search;  // Breaks outer loop!
                }
            }
        }

        if (foundRow != -1) {
            System.out.println("Found " + target + " at [" + foundRow + "][" + foundCol + "]");
        } else {
            System.out.println(target + " not found");
        }

    }
}
public class LabeledBreak {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int target = 9;

        int foundRow = -1;
        int foundCol = -1;

        // Without label: only breaks inner loop
        System.out.println("Search without label (broken):");
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break;  // Only breaks inner loop!
                }
            }
            System.out.println("Still in outer loop, row " + row);
        }

        // With label: breaks outer loop
        System.out.println("\nSearch with label (correct):");
        foundRow = -1;
        foundCol = -1;

        search:
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break search;  // Breaks outer loop!
                }
            }
        }

        if (foundRow != -1) {
            System.out.println("Found " + target + " at [" + foundRow + "][" + foundCol + "]");
        } else {
            System.out.println(target + " not found");
        }

    }
}
public class LabeledBreak {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int target = 99;

        int foundRow = -1;
        int foundCol = -1;

        // Without label: only breaks inner loop
        System.out.println("Search without label (broken):");
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break;  // Only breaks inner loop!
                }
            }
            System.out.println("Still in outer loop, row " + row);
        }

        // With label: breaks outer loop
        System.out.println("\nSearch with label (correct):");
        foundRow = -1;
        foundCol = -1;

        search:
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    foundRow = row;
                    foundCol = col;
                    break search;  // Breaks outer loop!
                }
            }
        }

        if (foundRow != -1) {
            System.out.println("Found " + target + " at [" + foundRow + "][" + foundCol + "]");
        } else {
            System.out.println(target + " not found");
        }

    }
}
  1. target ← 5, foundRow ← -1, foundCol ← -1

    1public class LabeledBreak {2    public static void main(String[] args) {3        int[][] grid = {4            {1, 2, 3},5            {4, 5, 6},6            {7, 8, 9}7        };8        int target→ 5 = 5;  //@target=1, 9, 999        10        int foundRow→ -1 = -1;11        int foundCol→ -1 = -1;12        13        // Without label: only breaks inner loop14        System.out.println("Search without label (broken):");15        for (int row = 0; row < grid.length; row++) {
    outputSearch without label (broken):
  2. for (int row = 0; row < grid.length; row++)

    pass 1 of 3
    14System.out.println("Search without label (broken):");15for (int row0 = 0; row < grid.length3; row++) {16    for (int col = 0; col < grid[row].length; col++) {
    All 3 passes — pass 1 is the card above
    passrowgrid[row][col]coltargetfoundRowfoundCol
    10
    2151511
    32
  3. for (int col = 0; col < grid[row].length; col++)

    pass 1 of 8
    15for (int row = 0; row < grid.length; row++) {16    for (int col0 = 0; col < grid[row].length3; col++) {17        if (grid[row][col] == target) {
    All 8 passes — pass 1 is the card above
    passcolrowgrid[row][col]targetfoundRowfoundCol
    100
    210
    320
    401
    5115511
    602
    712
    822
  4. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row0);24}
    outputStill in outer loop, row 0
  5. foundRow ← 1, foundCol ← 1

    16for (int col = 0; col < grid[row].length; col++) {17    if (grid[row][col]5 == target5) {18        foundRow→ 1 = row1;19        foundCol→ 1 = col1;20        break;  // Only breaks inner loop!21    }
  6. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row1);24}
    outputStill in outer loop, row 1
  7. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row2);24}
    outputStill in outer loop, row 2
  8. foundRow ← -1, foundCol ← -1

    26// With label: breaks outer loop27System.out.println("\nSearch with label (correct):");28foundRow→ -1 = -1;29foundCol→ -1 = -1;
    output
    Search with label (correct):
  9. if (foundRow != -1)

    42if (foundRow1 != -1) {43    System.out.println("Found " + target5 + " at [" + foundRow1 + "][" + foundCol1 + "]");44} else {
    outputFound 5 at [1][1]
  1. target ← 1, foundRow ← -1, foundCol ← -1

    1public class LabeledBreak {2    public static void main(String[] args) {3        int[][] grid = {4            {1, 2, 3},5            {4, 5, 6},6            {7, 8, 9}7        };8        int target→ 1 = 1;9        10        int foundRow→ -1 = -1;11        int foundCol→ -1 = -1;12        13        // Without label: only breaks inner loop14        System.out.println("Search without label (broken):");15        for (int row = 0; row < grid.length; row++) {
    outputSearch without label (broken):
  2. for (int row = 0; row < grid.length; row++)

    pass 1 of 3
    14System.out.println("Search without label (broken):");15for (int row0 = 0; row < grid.length3; row++) {16    for (int col = 0; col < grid[row].length; col++) {
    All 3 passes — pass 1 is the card above
    passrowgrid[row][col]coltargetfoundRowfoundCol
    1010100
    21
    32
  3. for (int col = 0; col < grid[row].length; col++)

    pass 1 of 7
    15for (int row = 0; row < grid.length; row++) {16    for (int col0 = 0; col < grid[row].length3; col++) {17        if (grid[row][col] == target) {
    All 7 passes — pass 1 is the card above
    passcolrowgrid[row][col]targetfoundRowfoundCol
    1001100
    201
    311
    421
    502
    612
    722
  4. foundRow ← 0, foundCol ← 0

    16for (int col = 0; col < grid[row].length; col++) {17    if (grid[row][col]1 == target1) {18        foundRow→ 0 = row0;19        foundCol→ 0 = col0;20        break;  // Only breaks inner loop!21    }
  5. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row0);24}
    outputStill in outer loop, row 0
  6. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row1);24}
    outputStill in outer loop, row 1
  7. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row2);24}
    outputStill in outer loop, row 2
  8. foundRow ← -1, foundCol ← -1

    26// With label: breaks outer loop27System.out.println("\nSearch with label (correct):");28foundRow→ -1 = -1;29foundCol→ -1 = -1;
    output
    Search with label (correct):
  9. if (foundRow != -1)

    42if (foundRow0 != -1) {43    System.out.println("Found " + target1 + " at [" + foundRow0 + "][" + foundCol0 + "]");44} else {
    outputFound 1 at [0][0]
  1. target ← 9, foundRow ← -1, foundCol ← -1

    1public class LabeledBreak {2    public static void main(String[] args) {3        int[][] grid = {4            {1, 2, 3},5            {4, 5, 6},6            {7, 8, 9}7        };8        int target→ 9 = 9;9        10        int foundRow→ -1 = -1;11        int foundCol→ -1 = -1;12        13        // Without label: only breaks inner loop14        System.out.println("Search without label (broken):");15        for (int row = 0; row < grid.length; row++) {
    outputSearch without label (broken):
  2. for (int row = 0; row < grid.length; row++)

    pass 1 of 3
    14System.out.println("Search without label (broken):");15for (int row0 = 0; row < grid.length3; row++) {16    for (int col = 0; col < grid[row].length; col++) {
    All 3 passes — pass 1 is the card above
    passrowgrid[row][col]coltargetfoundRowfoundCol
    10
    21
    3292922
  3. for (int col = 0; col < grid[row].length; col++)

    pass 1 of 9
    15for (int row = 0; row < grid.length; row++) {16    for (int col0 = 0; col < grid[row].length3; col++) {17        if (grid[row][col] == target) {
    All 9 passes — pass 1 is the card above
    passcolrowgrid[row][col]targetfoundRowfoundCol
    100
    210
    320
    401
    511
    621
    702
    812
    9229922
  4. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row0);24}
    outputStill in outer loop, row 0
  5. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row1);24}
    outputStill in outer loop, row 1
  6. foundRow ← 2, foundCol ← 2

    16for (int col = 0; col < grid[row].length; col++) {17    if (grid[row][col]9 == target9) {18        foundRow→ 2 = row2;19        foundCol→ 2 = col2;20        break;  // Only breaks inner loop!21    }
  7. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row2);24}
    outputStill in outer loop, row 2
  8. foundRow ← -1, foundCol ← -1

    26// With label: breaks outer loop27System.out.println("\nSearch with label (correct):");28foundRow→ -1 = -1;29foundCol→ -1 = -1;
    output
    Search with label (correct):
  9. if (foundRow != -1)

    42if (foundRow2 != -1) {43    System.out.println("Found " + target9 + " at [" + foundRow2 + "][" + foundCol2 + "]");44} else {
    outputFound 9 at [2][2]
  1. target ← 99, foundRow ← -1, foundCol ← -1

    1public class LabeledBreak {2    public static void main(String[] args) {3        int[][] grid = {4            {1, 2, 3},5            {4, 5, 6},6            {7, 8, 9}7        };8        int target→ 99 = 99;9        10        int foundRow→ -1 = -1;11        int foundCol→ -1 = -1;12        13        // Without label: only breaks inner loop14        System.out.println("Search without label (broken):");15        for (int row = 0; row < grid.length; row++) {
    outputSearch without label (broken):
  2. for (int row = 0; row < grid.length; row++)

    pass 1 of 3
    14System.out.println("Search without label (broken):");15for (int row0 = 0; row < grid.length3; row++) {16    for (int col = 0; col < grid[row].length; col++) {
    All 3 passes — pass 1 is the card above
    passrow
    10
    21
    32
  3. for (int col = 0; col < grid[row].length; col++)

    pass 1 of 9
    15for (int row = 0; row < grid.length; row++) {16    for (int col0 = 0; col < grid[row].length3; col++) {17        if (grid[row][col] == target) {
    All 9 passes — pass 1 is the card above
    passcolrow
    100
    210
    320
    401
    511
    621
    702
    812
    922
  4. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row0);24}
    outputStill in outer loop, row 0
  5. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row1);24}
    outputStill in outer loop, row 1
  6. System.out.println("Still in outer loop, row " + row);

    22    }23    System.out.println("Still in outer loop, row " + row2);24}
    outputStill in outer loop, row 2
  7. foundRow ← -1, foundCol ← -1

    26// With label: breaks outer loop27System.out.println("\nSearch with label (correct):");28foundRow→ -1 = -1;29foundCol→ -1 = -1;
    output
    Search with label (correct):
  8. else

    43    System.out.println("Found " + target + " at [" + foundRow + "][" + foundCol + "]");44} else {45    System.out.println(target99 + " not found");46}
    output99 not found

Labels let you break from nested loops - useful for searching 2D structures.

labeled break Java: `outer: for(...) { ... break outer; }` - break outer loop.

Exercise: Refactoring.java

Explore refactoring techniques to reduce break/continue for cleaner code