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 = ;
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 = ;
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 = ;
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
}
}
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));
}
}
}
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 = ;
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 = ;
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 = ;
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.");
}
}
}
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 = ;
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 = ;
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 = ;
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);
}
}
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 = ;
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 = ;
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 = ;
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 = ;
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");
}
}
}
Labels let you break from nested loops - useful for searching 2D structures.
@concept labeled break
Java: outer: for(...) { ... break outer; } - break outer loop.
Exercise: Refactoring.java
Explore refactoring techniques to reduce break/continue for cleaner code