Java Break Statement in Loops

(Last Updated On: February 25, 2019)

Learn how to use break statements in loops in java. Java code examples using break statement with for loop, while loop, do while loops and nested loops are provided to terminate them.

Break Statement in java

Break keyword is used to terminate for, do-while and while loop in java.  It breaks current flow to program from a loop at the specified condition in a loop and after terminating from a loop remaining code will be executed by program controller.

Prerequisite: You should know the following to understand break statement.

 

Break statement in for loop

In below java program, for loop is running 5 times and inside loop, we are checking if value of I is equal to 4 then loop will break and control will go outside of loop.So, after break statement is encountered, the System.out.println(i); will not execute.

 

Output:
1
2
3

Break statement in while loop

Same program example as above for loop. just for loop has been replaced with while loop.

 

 

Break statement in do while loop

Same program example as above for loop. just for loop has been replaced with do while loop.

 

 

 

Break statement in nested loop

We can also use break statement in nested loop. Nested loop means a loop inside a loop. In below java program example, we have used two while loops. In inner while loop we have used break statement.

Outer loop is running 5 times, inner while loop is running 3 times. But, in inner loop we have put a condition using if block. as soon as value of j will be equal to 2 the break statement in inner loop will be encountered and inner loop will break.

Note that outer loop will run 5 times as we have not used break with that.

 

Output:
Inner loop j value:1
Outer loop i value:1
Outer loop i value:2
Outer loop i value:3
Outer loop i value:4
Outer loop i value:5

 

NOTE:If you also want to break the outer loop, you have to use break for outer while loop too. See below example.

 

Output:
Inner loop j value:1
Outer loop i value:1
Outer loop i value:2