Break statement in java

Break statement in java is used to change the normal control flow of compound statement like while, do-while , for. Break statement is used in many languages such C, C++ etc. Sometimes it may happen that we want to come out of the loop in that case break  is used.

Break statement in java

Break statement in java is used to change the normal control flow of compound statement like while, do-while , for. Break statement is used in many languages such C, C++ etc. Sometimes it may happen that we want to come out of the loop in that case break  is used.

Break statement in java

Break statement in java

Break statement in java is used to change the normal control flow of  compound statement like while, do-while , for. Break statement is used in many languages such  C, C++  etc. Sometimes it may happen that we want to come out of the loop in that case break  is used. Break is used with for, while and do-while looping statement and break is also used in switch case. Break statement allow a force termination of  loop. Within a loop if a break statement is encountered then control resume to next statement and come out of the loop.

public class Break {
	public static void main(String args[]){
		
		System.out.println("Loop started");
		for(int i=1;i<=5;i++)
		{
			System.out.println(" i = "+ i);
			
		    if(i==4)
		    	break;
	   }
	      
	}
    }

In the above example inside a for loop we used break statement so if i value become 4(i = = 4), then the control will come out from the for loop. It will execute till 4.

Output : After executing the above program.

Break is also used in inner loop as follows in below program:

public class BreakInnerLoop {
	public static void main(String args[]){
		
		System.out.println("Loop started");
		for(int i=1;i<=5;i++)//outer loop
		{
			
			System.out.print("pass" +i+ " : ");
			
			for(int j=1;j<=10;j++)//inner loop
			{
				if(j==5)break;
				System.out.print(j+ " ");
			}
			System.out.println(" ");
		          } 
	            }
	
	       	}

As you can observe that when j become 5 it will exit from the inner for loop and then execute the remaining code.

Output: After compiling and executing of above program the output is follows: