In this lesson of our Java course, we will look at the Java break statement. The “Java break break” statement is one of the control flow statements in Java that is used to exit a loop or switch statement. In this article, we will discuss how the Java break statement works, how it can be used with nested loops, and the labeled break statement.
Table of Contents
1. How Java Break statement works?
The Java break statement is used to exit a loop or switch statement immediately. When the break statement is encountered, the program execution jumps out of the loop or switch statement and continues with the next statement after the loop or switch statement.
Java break statement is mostly used with a loop statement. For example, the following code uses the break statement to exit a while loop when the variable i is equal to 5:
int i = 0;
while (i < 10) {
if (i == 5) {
break;
}
System.out.println(i);
i++;
}
This code will print the numbers from 0 to 4 and the execution will exit the loop when the variable i is equal to 5.
2. Java Break and Nested Loop
Java break statement can also be used to exit a nested loop. When a break statement is encountered within a nested loop, it will only exit the innermost loop. For example, the following code uses nested loops and the break statement to find a specific number in a two-dimensional array:
int[][] numbers = {
{
1,
2,
3
},
{
4,
5,
6
},
{
7,
8,
9
}
};
outer: for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
if (numbers[i][j] == 5) {
System.out.println("Found 5 at index [" + i + "][" + j + "]");
break outer;
}
}
}
This code will search for the number 5 in the two-dimensional array and print the message “Found 5 at index [1][1]
” when it’s found, and the execution will exit the outer loop.
3. Labeled Break Statement
Java also provides the ability to use labeled break statements, which allow you to exit a specific loop, even if it’s nested within other loops. To use a labeled break statement, you first need to assign a label to the loop, and then use that label in the break statement. For example:
outer: for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if (j == 5) {
break outer;
}
System.out.print(i * j + " ");
}
System.out.println();
}
This code will exit the outer loop when the inner loop reaches the fifth iteration and it will not print the remaining of the multiplication table.
Summary
The Java break statement is a powerful control flow statement that can be used to exit a loop or switch statement. It can be used with an if statement to check specific conditions, and can also be used with nested loops to exit a specific loop. Additionally, labelled break statements can be used to exit a specific loop, even if it’s nested within other loops. Understanding how to use the break statement. As usual, you can check the source code on our GitHub Repository