Break

Branching Statements

Break

🙋 Need help? Ask an expert now!

In Java, there are branching statements, for example the break statement, which breaks the loop in the program and continues running the statements after the loop. If you have a for or while loop and you want it to stop after a certain condition is true, you can have a break statement inside the if statement. How is it implemented in code? Take a look below.

BreakStatementExample.java
package exlcode;

public class BreakStatementExample {

  public static int exampleVariableOne = 10;

  public static void main(String[] args) {
    System.out.println("Counting forward from 0-10:");
    for (int count = 0; count <= exampleVariableOne; count++) {
      System.out.print(count + " ");
      // once count is equal to 5, the break statement will
      // terminate the for loop
      if (count == 5) {
        break;
      }
    }
  }
}

The if statement has the expression "count == 5", so when count has a value of 5 the statements inside the if statement will be executed, including the break; statement, which will terminate the for loop so any number after 5 will not be printed. break; does not affect the if statement, it terminates the whole loop. When the break; statement is used appropriately, it saves time when running the program because you wouldn't have to loop through the same statements over and over again.

Edit Me on GitHub!

Application Question

Consider the following code segment:

int varOne = 0;
for (int count = 0; count < 20; count++)
{
  varOne ++;
  if (varOne > 3){
    break;
  }
}
System.out.println(varOne);

What is printed as a result of executing this code segment?