Break Statement in Java

By Preeti Jain Last updated : January 29, 2024

The break statement is used to break the execution of any loop or to break (come out from a particular case body) the switch cases in the switch statement.

The break statement interrupts the flow of the loop at certain conditions, in case of multiple loops, the break statement only breaks that loop in which break is used.

Syntax

Use the following statement of break statement:

break;

The syntax is a simple break keyword, used within the loop body or after the switch case statements.

Flow Chart

Understand the concept of break statement in a loop through the following flowchart:

break statement in java

Example

Here is an example of how to use the break statement in Java:

public class Main {
  public static void main(String arg[]) {
    int i;
    // loop
    for (i = 1; i <= 12; i++) {
      // breaking when the value of i is 8
      if (i == 8) {
        break;
      }
      System.out.println(i);
    }
  }
}

The output of the above example is:

1
2
3
4
5
6
7

In this program, the loop is running from 1 to 12 and we are using break inside the if condition (i==8). So, when value of i will be 8, loop execution will be stopped and program’s execution will jump to the next statement written just after the loop body.

 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.