break statement in java

Let’s learn break statement in java.

break statement in java

When break statement is encountered in a loop, that loop will terminate and the control will shift to next statement of the same loop.

break statement and continue statement are the two important concepts.

Syntax:

break;


break statement is used to break loop in switch statement. break statement can also be used in all types of loops namely while loop, do-while loop and for loop. Here’s how break statement works in all loops.

break statement in java

Let’s see an example on break statement.

public class BreakStatementExample
{
   public static void main(String[] args) 
   {
      for(int a = 1; a <= 10; a++)
      {
         if(a == 3)
         {  
            // breaking loop  
            break;  
         }  
         System.out.println(a);  
      }
   }
}


Output:

1
2


break statement in inner loop – inner loop terminates only if you use break statement inside inner loop. Let’s see program to demonstrate use of break statement inside inner loop.

public class BreakStatementInnerLoop
{
   public static void main(String[] args)
   {
      // outer loop
      for(int a = 1; a <= 5; a++)
      {
         // inner loop  
         for(int b = 1; b <= 5; b++)
         {
            if(a == 3 && b == 3)
            {
               // using break statement inside inner loop
               break;    
            }
            System.out.println(a + " " + b);    
         }    
      }
   }
}


Output:

1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
2 5
3 1
3 2
4 1
4 2
4 3
4 4
4 5
5 1
5 2
5 3
5 4
5 5


break statement in for loop

Since JDK 1.5 we can use break statement in for loop with a label. By using this feature we can break any loop either outer or inner loop.

public class BreakStatementForLoop
{
   public static void main(String[] args) 
   {
      aa:
      for(int a = 5; a <= 7; a++)
      {  
         bb:  
         for(int b = 5; b <= 7; b++)
         {  
            if(a == 6 && b == 6)
            {  
               // use break statement with label  
               break aa;    
            }    
            System.out.println(a + " " + b);    
         }    
      }
   }
}


Output:

5 5
5 6
5 7
6 5


break statement in while loop

public class BreakStatementWhileLoop
{
   public static void main(String[] args) 
   {
      int a = 1;
      while(a <= 10)
      {
         if(a == 7)
         {
            a++;  
            break;// break the loop  
         }  
         System.out.println(a);  
         a++;
      }
   }
}


Output:

1
2
3
4
5
6


break statement in do-while loop

public class BreakStatementDoWhileLoop
{
   public static void main(String[] args) 
   {
      int a = 1;  
      do
      {
         if(a == 7)
         {
            a++;  
            break; // break the loop  
         }
         System.out.println(a); 
         a++;
      }while(a <= 10);
   }
}


Output:

1
2
3
4
5
6