print
Advertisment
Advertisment

Break statement in java

Java break statement is used to break a loop or switch statement. It breaks the current flow of the program in the specified condition. In the case of the inner loop, it breaks only the inner loop. When a break statement is used inside a loop, the loop terminates immediately at the break condition and program control is resumed at the next statement in the loop after the loop ends. We can use break statements in all types of loops such as in for loop, while loop, and do-while loop.

Syntax


for(;;){
  if(condition statement){
    break;
  }
}

java break statement with use for loop

class For_loop{
  public static void main(String[] args) {
    for(char c='a';c<='z';c++){
      if(c=='g'){
        break;
      }
      System.out.println(c);
    }
  }
}

Output :


 a
 b
 c
 d
 e
 f

java break statement with use while loop

class While_loop{
  public static void main(String[] args) {
    int a = 1;  
    while(a<=5){
    if(a==2){
      switch(a){
         case 1:
         System.out.println("First case");
         break;
         case 2:
         System.out.println("Second case");
         break;
         case 3:
         System.out.println("Third case");
         break;
      }
    }
     a++;
    }
  }
}

Output :


  Second case
Advertisment

java break statement with a use switch statement

 class Switch_statement{
  public static void main(String[] args) {
    String name = "Ramakant";
    switch(name){
      case "Aman":
        System.out.println("Case Aman");
      break;
      case "Ramakant":
        System.out.println("Case Ramakant");
      break;
      case "Sunny":
        System.out.println("Case Sunny");
      break;
      default:
        System.out.println("Case don't' match");
    }  
  }
}

Output :

 
  
    Case Ramakant
  

java break statement with use do-while statement

 class Do_while {  
  public static void main(String[] args) {  
    int i=1;  
    do{  
      if(i==5){  
        break;
      }
      System.out.println(i);  
      i++;  
    }while(i<=10);  
  }  
}

Output :


    1
    2
    3
    4
Advertisment

Java Break Statement with use Inner Loop

It breaks the inner loop only if you use a break statement inside the inner loop.

class BreakExample {  
  public static void main(String[] args) {
    for(int i=1;i<=3;i++){
      for(int j=1;j<=3;j++){
        if(i==2&&j==2){    
            break;
        }
        System.out.println(i+" "+j);    
      }
    }
  }
}

Output :


    1 1
    2 2
    3 3
    2 1
    3 1
    3 2
    3 3
Advertisment
Advertisment
arrow_upward