Sitemap
Adam Langmesser

Adam Langmesser

Break with labeled statement in Java

2 min readMay 3, 2026

If you used Java or any modern programming language you probably used break statement. In this article I want to show you a break statement used in a looptogether with a so called label or labeled statement.

Typically you can use break in a loop like that:

for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + " j = " + j);
if (j == 2) break; // omit every iteration with j > 2
}
System.out.println();
}

Above code prints to the console:

i = 1 j = 1
i = 1 j = 2

i = 2 j = 1
i = 2 j = 2

i = 3 j = 1
i = 3 j = 2

So a break statement on it’s own in a loop allows program to leave the loop body in which it was used and cancled all leftover iterations of that loop.

Get Adam Langmesser’s stories in your inbox

Join Medium for free to get updates from this writer.

But in Java, there is a way to enhance this capability — labeled statement

my_annotation:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + " j = " + j);
if (j == 2) break my_annotation;
}
System.out.println();
}

Here I’ve put a labeled statement with a name my_annotation. Now the output looks like that:

i = 1 j = 1
i = 1 j = 2

As you can see, a labeled break allows us to exit a labeled outer loop directly from within an inner loop.

--

--