Learn how to use java break statement in loop and switch case with this tutorial. Java break statement can be used in loops to terminate the iteration. When the break statement comes inside the loop, the control immediately comes out of the loop to the next statement.

Java Break Statement

If the program contains the inner loop and the break comes under the nested loop, the break statement will terminate the inner loop and not the outer loop. A java break statement can be used with the for loop, while loop and switch case also.

Below are the descriptions and examples within each one.

Example of Java Break Statement in Switch Case

You can use the java break statement with each switch cases. If any case match with the given condition the statement under that case will get executed. However, if you do not use the break statement in each case, the other cases below the matched case will also get executed.

Example1:

Output

case2:The student is Excellent in the study.

The above example contains the break statement with each case. The second case matches with the condition and executes the statement under this condition. The break statement then terminate the switch case and move the control from switch case. If you want to learn more about the switch case, you can read our tutorial on Java switch case conditional statement.

Example of Java Break Statement in For Loop

If you want to print the numbers and create a simple java program. Suppose your program print numbers from 0 to 9 and you do not want to print number greater than five. You can use the if condition inside which you can use the break statement to terminate the loop.

Example2

Output

0
1
2
3
4
5

The above example prints the numbers from 0 to 5 and the loop gets terminated using the break statement. However, In addition to this, you also use the break statement inside the nested loop and terminate the inner loop using the break statement. If you want to learn more about the for loop, you can read our tutorial on Java for loop with example.

Example of Java Break Statement in While Loop

A while loop here prints the numbers from 0 to 5 using the break statement. If you remove the break statement from the while loop, the loop prints the numbers from 0 to 9. This is a simple while loop program. I am using the if condition here, inside which a break statement comes to break the loop and move the control out of the loop.

Example3

Output

0
1
2
3
4
5

If you want to learn more about the while loop, you can read our tutorial on Java while and do while loop with the example.

Reference
Oracle Java Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.