Break Java

 
The break statement is a control statement which is used to jump out of the loop.

Types of break statement:

1. Unlabeled Break statement: is used to jump out of the loop when specific condition returns true.
2. Labeled Break Statement: is used to jump out of the specific loop based on the label when specific condition returns true.

Syntax of Unlabeled Break statement:

for( initialization; condition; statement){ 
        //Block of statements
         if(condition){
                break;
         }
}

Program to use for loop break statement example in java

/**
 * Program to use for loop break statement example in java.
 * @author W3spoint
 */
public class ForLoopBreakExample {	
	static void forLoopBreakTest(int num){
		//For loop test
		 for(int i=1; i<= num; i++){
			 if(i==6){
				 //Break the execution of for loop.
				 break;
			 }
			 System.out.println(i);            
                 }
	}	
 
	public static void main(String args[]){ 
		//method call 
		forLoopBreakTest(10); 
	}
}

Output:

1
2
3
4
5

Syntax of Labeled Break Statement:

Label1:
for( initialization; condition; statement){ 
     Label2:
     for( initialization; condition; statement){ 
        //Block of statements
         if(condition){
                break Label1;
         }
     }
}

Program to use for loop break label statement in java.

/**
 * Program to use for loop break label statement in java.
 * @author W3spoint
 */
public class ForLoopBreakLabelExample {	
	static void forLoopBreakLabelTest(int num1, int num2){
		//For loop break label test
		Outer:
		 for(int i=1; i<= num1; i++){
			 Inner:
			 for(int j=1; j<= num2; j++){
				 if(i + j == 8){
					 //Break the execution of Outer for loop.
					 break Outer;
				 }
				 System.out.println(i + j);    
			 }			         
                 }
	}	
 
	public static void main(String args[]){ 
		//method call 
		forLoopBreakLabelTest(10, 5); 
	}
}

Output:

2
3
4
5
6
3
4
5
6
7
4
5
6
7

 

Content Protection by DMCA.com
Please Share