Control Flow
Break and Continue
Loop Control
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.
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
}
}
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++) {for (int i = 0; i < numbers.length; i++)
pass 1 of 46int 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: 10All 4 passes — pass 1 is the card above pass inumbers[i]targetfoundIndex1 0 10 — — 2 1 25 — — 3 2 30 — — 4 3 42 42 3 foundIndex ← 3
8System.out.println("Checking index " + i + ": " + numbers[i]);9if (numbers[i]42 == target42) {10 foundIndex→ 3 = i3;11 break; //#?break_exit12}if (foundIndex != -1)
15if (foundIndex3 != -1) {16 System.out.println("Found " + target42 + " at index " + foundIndex3);17} else {outputFound 42 at index 3
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++) {for (int i = 0; i < numbers.length; i++)
pass 1 of 36int 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: 10All 3 passes — pass 1 is the card above pass inumbers[i]targetfoundIndex1 0 10 — — 2 1 25 — — 3 2 30 30 2 foundIndex ← 2
8System.out.println("Checking index " + i + ": " + numbers[i]);9if (numbers[i]30 == target30) {10 foundIndex→ 2 = i2;11 break;12}if (foundIndex != -1)
15if (foundIndex2 != -1) {16 System.out.println("Found " + target30 + " at index " + foundIndex2);17} else {outputFound 30 at index 2
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++) {for (int i = 0; i < numbers.length; i++)
pass 1 of 66int 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: 10All 6 passes — pass 1 is the card above pass inumbers[i]target1 0 10 — 2 1 25 — 3 2 30 — 4 3 42 — 5 4 55 — 6 5 60 99 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.
Skip invalid entries (continue)
Skip items that don't meet criteria without stopping the loop.
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));
}
}
}
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:sum ← 85, count ← 1
pass 1 of 78System.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: 85All 7 passes — pass 1 is the card above pass scoresumcount1 85 0 → 85 0 → 1 2 -1 — — 3 92 85 → 177 1 → 2 4 0 177 2 → 3 5 78 177 → 255 3 → 4 6 -5 — — 7 95 255 → 350 4 → 5 if (score < 0)
pass 1 of 29for (int score : scores) {10 if (score-1 < 0) { //#?skip_invalid11 System.out.println(" Skipping invalid: " + score-1);12 continue;13 }output Skipping invalid: -1if (score < 0)
pass 2 of 29for (int score : scores) {10 if (score-5 < 0) { //#?skip_invalid11 System.out.println(" Skipping invalid: " + score-5);12 continue;13 }output Skipping invalid: -5System.out.println("Valid scores: " + count);
19System.out.println("Valid scores: " + count5);20System.out.println("Sum: " + sum350);21if (count > 0) {outputValid scores: 5 Sum: 350if (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.
Early exit on error
Stop processing if something goes wrong.
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.");
}
}
}
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;for (String cmd : commands)
pass 1 of 38for (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 pass cmdsuccess1 load — 2 process — 3 error false 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!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.
success ← true
1public class EarlyExit {2 public static void main(String[] args) {3 String[] commands = {"init", "run", "complete"};4 5 boolean success→ true = true;for (String cmd : commands)
pass 1 of 37for (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 pass cmdsuccess1 init — 2 run — 3 complete true if (success)
20if (successtrue) {21 System.out.println("All commands completed successfully.");22} else {outputAll commands completed successfully.
success ← true
1public class EarlyExit {2 public static void main(String[] args) {3 String[] commands = {"start", "stop"};4 5 boolean success→ true = true;for (String cmd : commands)
pass 1 of 27for (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.for (String cmd : commands)
pass 2 of 27for (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.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.
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);
}
}
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):sum ← 10
pass 1 of 510for (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: 10All 5 passes — pass 1 is the card above pass valuesum1 10 0 → 10 2 20 10 → 30 3 30 30 → 60 4 40 60 → 100 5 -1 — 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.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:sum2 ← 10, i ← 1
pass 1 of 424int 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 pass data[i]sum2i1 10 0 → 10 0 → 1 2 20 10 → 30 1 → 2 3 30 30 → 60 2 → 3 4 40 60 → 100 3 → 4 System.out.println("Sum: " + sum2);
28}29System.out.println("Sum: " + sum2100);outputSum: 100
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):sum ← 5
pass 1 of 49for (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: 5All 4 passes — pass 1 is the card above pass valuesum1 5 0 → 5 2 10 5 → 15 3 15 15 → 30 4 -1 — 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.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:sum2 ← 5, i ← 1
pass 1 of 323int 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 pass data[i]sum2i1 5 0 → 5 0 → 1 2 10 5 → 15 1 → 2 3 15 15 → 30 2 → 3 System.out.println("Sum: " + sum2);
27}28System.out.println("Sum: " + sum230);outputSum: 30
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):sum ← 100
pass 1 of 49for (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: 100All 4 passes — pass 1 is the card above pass valuesum1 100 0 → 100 2 200 100 → 300 3 300 300 → 600 4 400 600 → 1000 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:sum2 ← 100, i ← 1
pass 1 of 423int 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 pass data[i]sum2i1 100 0 → 100 0 → 1 2 200 100 → 300 1 → 2 3 300 300 → 600 2 → 3 4 400 600 → 1000 3 → 4 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.
Labeled break (nested loops)
Break out of outer loops using labels (Java-specific).
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");
}
}
}
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):for (int row = 0; row < grid.length; row++)
pass 1 of 314System.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 pass rowgrid[row][col]coltargetfoundRowfoundCol1 0 — — — — — 2 1 5 1 5 1 1 3 2 — — — — — for (int col = 0; col < grid[row].length; col++)
pass 1 of 815for (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 pass colrowgrid[row][col]targetfoundRowfoundCol1 0 0 — — — — 2 1 0 — — — — 3 2 0 — — — — 4 0 1 — — — — 5 1 1 5 5 1 1 6 0 2 — — — — 7 1 2 — — — — 8 2 2 — — — — 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 0foundRow ← 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 }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 1System.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 2foundRow ← -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):if (foundRow != -1)
42if (foundRow1 != -1) {43 System.out.println("Found " + target5 + " at [" + foundRow1 + "][" + foundCol1 + "]");44} else {outputFound 5 at [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):for (int row = 0; row < grid.length; row++)
pass 1 of 314System.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 pass rowgrid[row][col]coltargetfoundRowfoundCol1 0 1 0 1 0 0 2 1 — — — — — 3 2 — — — — — for (int col = 0; col < grid[row].length; col++)
pass 1 of 715for (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 pass colrowgrid[row][col]targetfoundRowfoundCol1 0 0 1 1 0 0 2 0 1 — — — — 3 1 1 — — — — 4 2 1 — — — — 5 0 2 — — — — 6 1 2 — — — — 7 2 2 — — — — 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 }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 0System.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 1System.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 2foundRow ← -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):if (foundRow != -1)
42if (foundRow0 != -1) {43 System.out.println("Found " + target1 + " at [" + foundRow0 + "][" + foundCol0 + "]");44} else {outputFound 1 at [0][0]
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):for (int row = 0; row < grid.length; row++)
pass 1 of 314System.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 pass rowgrid[row][col]coltargetfoundRowfoundCol1 0 — — — — — 2 1 — — — — — 3 2 9 2 9 2 2 for (int col = 0; col < grid[row].length; col++)
pass 1 of 915for (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 pass colrowgrid[row][col]targetfoundRowfoundCol1 0 0 — — — — 2 1 0 — — — — 3 2 0 — — — — 4 0 1 — — — — 5 1 1 — — — — 6 2 1 — — — — 7 0 2 — — — — 8 1 2 — — — — 9 2 2 9 9 2 2 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 0System.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 1foundRow ← 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 }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 2foundRow ← -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):if (foundRow != -1)
42if (foundRow2 != -1) {43 System.out.println("Found " + target9 + " at [" + foundRow2 + "][" + foundCol2 + "]");44} else {outputFound 9 at [2][2]
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):for (int row = 0; row < grid.length; row++)
pass 1 of 314System.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 pass row1 0 2 1 3 2 for (int col = 0; col < grid[row].length; col++)
pass 1 of 915for (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 pass colrow1 0 0 2 1 0 3 2 0 4 0 1 5 1 1 6 2 1 7 0 2 8 1 2 9 2 2 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 0System.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 1System.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 2foundRow ← -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):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.
Exercise: Refactoring.java
Explore refactoring techniques to reduce break/continue for cleaner code