Understanding Java’s Break Statement

When working with loops, there may be instances where you need to skip certain statements or exit the loop entirely. This is where Java’s break statement comes in. In this article, we’ll explore how the break statement works, its syntax, and provide examples of its usage.

What is the Break Statement?

The break statement in Java terminates a loop immediately, transferring control to the next statement following the loop. It is commonly used with decision-making statements, such as if-else statements.

Syntax of the Break Statement

The syntax of the break statement is simple:

java
break;

How the Break Statement Works

Let’s take a look at an example to understand how the break statement works:

java
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}

In this example, the loop will iterate until i reaches 5, at which point the break statement is executed, terminating the loop.

Java Break and Nested Loop

When working with nested loops, the break statement terminates the innermost loop. Here’s an example:

java
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j == 5) {
break;
}
System.out.println(j);
}
}

In this example, the break statement terminates the innermost loop, but the outer loop continues to execute.

Labeled Break Statement

Java also provides a labeled break statement, which allows you to specify which loop to terminate. Here’s an example:

java
outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j == 5) {
break outer;
}
System.out.println(j);
}
}

In this example, the break statement terminates the outer loop, rather than the inner loop.

Example: Labeled Break Statement

Here’s another example of using a labeled break statement:

java
first:
for (int i = 0; i < 10; i++) {
second:
for (int j = 0; j < 10; j++) {
if (j == 5) {
break second;
}
System.out.println(j);
}
}

In this example, the break statement terminates the loop labeled “second”.

Leave a Reply

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