Member-only story
Hi everyone, welcome back. In this article, we will be going over the break statement in Java and see how it works. The break statement is used to break out of a loop meaning we will no longer loop, even if there are additional iterations left. This can be done within a for loop or a while loop and we will go over an example of both. With this introduction out of the way, let’s get into it.
Example: Breaking Out of a For Loop
Let’s see an example of us breaking out of a for loop:
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}Output:
0
1
2
As we can see in the example above, we are executing our break statement when our ‘i’ variable reaches 3. Looking at the output, we see that we successfully looped through the values of 0, 1, and 2, but nothing else. This verifies that we have broken out of our for loop after ‘i’ was equal to 3.
Example: Breaking Out of a While Loop
Now, let’s see an example of us breaking out of a while loop:
int i = 0;
while (i < 5) {
if (i == 3) {
break;
}
System.out.println(i);
i++;
}Output:
0
1
2