Break statement in Java

 Java break statement

As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

BreakExample.java

  1. public class BreakExample {  
  2.   
  3. public static void main(String[] args) {  
  4. // TODO Auto-generated method stub  
  5. for(int i = 0; i<= 10; i++) {  
  6. System.out.println(i);  
  7. if(i==6) {  
  8. break;  
  9. }  
  10. }  
  11. }  
  12. }  

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

Calculation.java

  1. public class Calculation {    
  2.     
  3. public static void main(String[] args) {    
  4. // TODO Auto-generated method stub    
  5. a:    
  6. for(int i = 0; i<= 10; i++) {    
  7. b:    
  8. for(int j = 0; j<=15;j++) {    
  9. c:    
  10. for (int k = 0; k<=20; k++) {    
  11. System.out.println(k);    
  12. if(k==5) {    
  13. break a;    
  14. }    
  15. }    
  16. }    
  17.     
  18. }    
  19. }    
  20.     
  21.     
  22. }    

Output:

0
1
2
3
4
5


Comments

Popular Topics

What is JSP. How to create one JSP application in Eclipse

How to develop a RESTful webservice in java ?

Data Types in PL/SQL

What is JDBC ?

What is Hibernate in java ?

If you have any query or suggestions, Please feel free to write us

Name

Email *

Message *