Program Flow  «Prev  Next»
Lesson 9Breaking out of loops
Objective Learn how to break out of loops using the break statement.

Breaking Out of Loops

If you recall from earlier in the module, every case section of a switch statement typically ends with a break statement. To refresh your memory, take a look at the following example:
switch (score) {
 case 1:
   rating = "Poor";
   break;
 case 2:
   rating = "Below Average";
   break;
 case 3:
   rating = "Average";
   break;
 default:
   rating = "Undefined";

The break statement in this code is used to exit out of the switch statement so that no other code is executed. The break statement can also be used in loops to exit out of a loop and bypass the loop condition. Following is an example of getting out of an infinite loop with a break statement:
int i = 0;
while (true) {
  System.out.println("Keeps on going...");
  if (++i > 99)
    break;
}


When to make use of the break statement in your Java code

The `break` statement in Java is used to control the flow of execution within loops or switch statements. As a Java SE 17 developer, you should use the `break` statement in the following scenarios:
  1. Exiting a Loop Early
    • Use break to terminate a for, while, or do-while loop before its normal termination condition is met. This is helpful when you have found the desired result or condition, and further iterations are unnecessary.
          for (int i = 0; i < 10; i++) {
              if (i == 5) {
                  break; // Exit the loop when i equals 5
              }
              System.out.println("i = " + i);
          }
        
  2. Switch Statements
    • In a switch block, break is used to terminate a case and prevent "fall-through" to subsequent cases unless fall-through is explicitly desired.
          int day = 3;
          switch (day) {
              case 1:
                  System.out.println("Monday");
                  break;
              case 2:
                  System.out.println("Tuesday");
                  break;
              case 3:
                  System.out.println("Wednesday");
                  break; // Without this break, execution would continue to case 4
              case 4:
                  System.out.println("Thursday");
                  break;
              default:
                  System.out.println("Other day");
          }
        
  3. Enhanced Switch Statement (Java SE 17 Feature)
    • When using the enhanced switch expression introduced in modern Java, you don't explicitly need break since each case is treated as an isolated expression or block. However, you can still use it if you want to exit loops or nested blocks within the case body.
          int month = 2;
          switch (month) {
              case 1, 2, 3 -> System.out.println("Q1");
              case 4, 5, 6 -> System.out.println("Q2");
              case 7, 8, 9 -> System.out.println("Q3");
              case 10, 11, 12 -> System.out.println("Q4");
              default -> System.out.println("Invalid month");
          }
        
  4. Breaking Out of Nested Loops
    • Use break with labels to exit from nested loops. This is particularly useful when you need to break out of multiple levels of loops.
          outerLoop:
          for (int i = 0; i < 5; i++) {
              for (int j = 0; j < 5; j++) {
                  if (i == 3 && j == 3) {
                      break outerLoop; // Exit both loops
                  }
                  System.out.println("i = " + i + ", j = " + j);
              }
          }
        
When to Avoid Using `break`
  1. Readability: Overuse of break can make your code less readable. Use it judiciously and document why it’s necessary.
  2. Design Alternatives: If you find yourself relying heavily on break, consider whether restructuring your code with helper methods, flags, or conditions could improve clarity.
The `break` statement is a powerful tool when used correctly. In Java SE 17, its usage remains largely unchanged, but you should integrate it thoughtfully within modern constructs like the enhanced `switch` statement to maintain clean and efficient code.

break Statement

The effect of the break statement is to terminate the current loop, whether it be a while, for, for-each, or do-while statement. It is also used in the switch statement. The break statement passes control to the next statement following the loop. The break statement consists of the break keyword.
Consider the effect of the following statement sequence which repeatedly prompts the user for a command within an infinite loop. The loop will be terminated when the user enters the Quit command:
String command;
while (true) {
  System.out.print("Enter a command: "); 
 Scanner scanner = new Scanner(System.in);
 command = scanner.next();
 if ("Add".equals(command)) {
  // Process Add command
 }else if ("Subtract".equals(command)) {
  // Process Subtract command
 } else if ("Quit".equals(command)) {
 break;
} else {
 System.out.println("Invalid Command");
}
}

Notice how the equals method is used. The equals method is executed against the string literal and the command is used as its argument. This approach avoids NullPointerException that will result if the command contains a null value. As the string literals are never null, this exception will never occur.


while-loop

Normally this while loop would infinitely repeat due to the fixed loop condition of true.However, the break statement offers a way out by breaking out of the loop after one hundred iterations (0-99). The continue statement is similar to the break statement, and is used to skip to the next iteration of a loop. The following example shows how to use a continue statement to print only the odd numbers between 1 and 100:
for (int i = 1; i <= 100; i++) {
  if ((i % 2) != 1)
    continue;
  System.out.println(i);
}

Break Statement - Exercise


Practice using the break statement in this exercise.
Break Statement - Exercise


SEMrush Software