I’m trying to use a label with continue
in Java but getting an error.
Here’s my code:
public class Test {
public static void main(String[] args) {
continue s;
System.out.println("I am not supposed to print this");
s:
System.out.println("I am supposed to print this");
}
}
The error I get is:
java: undefined label: s
What am I doing wrong, and how should I properly use java jump
statements like continue
or break
with labels?
Labels must be placed before a loop, and continue must be inside that loop:
public class Test {
public static void main(String[] args) {
s: // Label before the loop
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue s; // Skips the current iteration and jumps to the next loop iteration
}
System.out.println("i: " + i);
}
}
}
Expected Output:
i: 0
i: 1
i: 3
i: 4
The label must be before the loop.
continue s; skips only when i == 2, so i: 2 is missing.
If you want to exit an outer loop, use break with a label:
public class Test {
public static void main(String[] args) {
s: // Label before the loop
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == 2 && j == 2) {
break s; // Exits both loops when i = 2 and j = 2
}
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
Expected Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
...
i: 1, j: 4
i: 2, j: 0
i: 2, j: 1
When i == 2 && j == 2, both loops exit using break s;.
This works only inside a loop.
If you’re inside a method and want to exit early (similar to a jump statement), you can use return:
public class Test {
public static void main(String[] args) {
printNumbers();
System.out.println("This will not print after return.");
}
public static void printNumbers() {
for (int i = 0; i < 5; i++) {
if (i == 2) {
return; // Exits the method completely
}
System.out.println("i: " + i);
}
System.out.println("This will not print if i == 2");
}
}
Expected Output:
i: 0
i: 1
Why?
When i == 2, return exits the method immediately.
Unlike break, which exits only a loop, return stops method execution.