Tutorials

Java Loop Control


Java break statement


Loop control statement that works with loop controls are:
  • Break statement (also works with switch-case)
  • Continue statement

Break Statement

Break statement in java can be used for the following purpose:
  • When break statement is found within a loop (for, while) then the loop execution is terminated immediately and execution control passes to immediate next line after the loop.
  • Break statement is used to terminate the case of switch case statement. 
Example 1: break statement with for loop.
 
public class breakExample {

    public static void main(String[] args) {
      for(int i=1; i<10; i++){
        if(i==3){
        break;
        }
      System.out.println("value of i="+ i);
     }
    System.out.println("Line after loop ends");

   }

}

OUTPUT:
value of i=1
value of i=2
Line after loop ends 
 

How our code works?

As per normal for loop execution process, if break statement was not used in our code, then we should have got output as “value of i=1” till “value of i=10”
 
But since break is applied for condition, if(i==3), so after second iteration finishes value of i is 3. This is where controls enters within if loop and here it encounters break statement. 
 
According to its property, break statement terminates the ‘for loop’ within which it was iterating thus ending the for loop’s life cycle. And thus nothing is executed for 3rd iteration after break is encountered ending the for loop execution. This is how we get output as:
value of i=1
value of i=2
 
Once i is 3, loop execution ends and the immediate next line will get executed. Thus we get output ‘Line after loop ends’ 
 
Example 2: break statement with nested for loop.
 
In nested for loop, if break is encountered within the inner for loop then only inner loop will terminate.
public class breakExample {

public static void main(String[] args) {
for(int i=1; i<5; i++){
for(int j=1; j<5; j++){
if(i==3){
break;
}
System.out.println("i="+ i+ "j="+ j);
}
}
System.out.println("Line after loop ends");

}

}


OUTPUT:
i=1j=1
i=1j=2
i=1j=3
i=1j=4
i=2j=1
i=2j=2
i=2j=3
i=2j=4
i=4j=1
i=4j=2
i=4j=3
i=4j=4
Line after loop ends
 
Note: Nothing is printed for (i=3) iteration since when i is 3 we apply break statement in inner for loop thus the inner for loop is terminated for the 3rd iteration(i=3)of outer for loop. So we do not have any output for i=3 (verify the same from output section).
 
Once inner loop is terminated the outer loop will again take the control and start executing its task.
 
TODO: Write same code with while loop.
 
Example: To learn use of break statement with switch case, please visit java break statement page present in Decision Making Statement section of this tutorial. 


Please Share this page
Views : 135
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!