Last Updated: 28 May, 2022
A break statement is used to terminate the current processing of loop or switch statements, after the termination control returns from the loop immediately to the next statement after the loop.
If we are using a break statement inside an inner loop then it breaks only the inner loop.
Java break statement Syntax:
break;
Basically, The break statement is useful when a certain condition meets in a loop and there is there no further iteration required then we use the break statement to terminate the loop.
Now will see how to use the break statement in for loop.
Let's understand it with the help of the given diagram and example below.
Example 1 : 'break' statement inside 'for' Loop
Output
1
2
3
4
You are out of for loop...
We can use a break statement with nested loops as well, if used inside a set of nested loops, will only break out of the innermost loop.
Example 2 : 'break' statement inside nested 'for' Loop
Output
i value = 1 j value = 1
i value = 1 j value = 2
i value = 1 j value = 3
i value = 2 j value = 1
i value = 3 j value = 1
i value = 3 j value = 2
i value = 3 j value = 3
You are out of all the for loop...
A labeled break statement is used to terminate the outer loop, the loop should be labeled for it to work. We are using this feature from JDK 1.5 version onwards.
Example 3 : 'break' statement used with labled 'for' Loop
Output
i = 1 j = 1
i = 1 j = 2
i = 2 j = 1
You are out of for loop...
Same as for loop we can also use break statement with while loop there is no any difference in the output.
Example 3 : 'break' statement inside 'while' Loop
Output
1
2
3
4
You are out of while loop...
Use a break statement in the do-while loop.
Let's understand it with the help of the given diagram and example below:
Example 4 : 'break' statement inside 'do-while' Loop
Output
1
2
3
4
You are out of do-while loop...
Same as loop statements we can also use the break statement inside the switch statement. To learn more, navigate to Java switch statement.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com