Jump statements transfer program execution control unconditionally to another part of the program. Java provides two primary loop jump statements: break and continue, both of which support unlabeled and labeled variants.
The break statement terminates the current loop immediately. Execution resumes at the first statement following the loop closing brace:
for (int i = 1; i <= 10; i++) {
if (i == 6) {
System.out.println("Target 6 found! Breaking out of loop.");
break; // Loop terminates immediately when i is 6
}
System.out.print(i + " ");
}
// Output: 1 2 3 4 5 Target 6 found! Breaking out of loop.
The continue statement skips the remainder of the current loop iteration and immediately jumps to the next cycle (evaluating the step update in a for loop, or the boolean condition in a while loop):
for (int i = 1; i <= 6; i++) {
if (i % 2 == 0) {
continue; // Skips even numbers
}
System.out.print(i + " ");
}
// Output: 1 3 5 (Even numbers 2, 4, 6 skipped!)
In deeply nested loops, standard break and continue only affect the innermost enclosing loop. To break or continue an outer loop from deep within an inner loop, use Labels:
public class LabeledLoopDemo {
public static void main(String[] args) {
// Outer loop labeled as 'outerLoop'
outerLoop:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
if (row == 2 && col == 2) {
System.out.println("Breaking directly out of outerLoop at [2,2]!");
break outerLoop; // Exits BOTH inner and outer loops!
}
System.out.println("Row: " + row + ", Col: " + col);
}
}
System.out.println("Execution resumed after outerLoop.");
}
}
Row: 1, Col: 1
Row: 1, Col: 2
Row: 1, Col: 3
Row: 2, Col: 1
Breaking directly out of outerLoop at [2,2]!
Execution resumed after outerLoop.
Exam Question: "Is 'goto' a keyword in Java? Why does Java not allow using it?"
Answer: goto is a reserved keyword in Java (meaning you cannot name a variable or class goto), but it has no function and cannot be used. James Gosling intentionally excluded goto to prevent programmers from writing unstructured "spaghetti code" that causes unpredictable jumps, memory corruptions, and debugging nightmares.
Congratulations on completing Control Flow & Loops! Let us now step into the crown jewel of Java: Object-Oriented Programming (OOP). Proceed to: OOP 4 Pillars in Java →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Iterating through loops.
Using break in switch cases.
Breaking out of while loops.
Entering Section 3: OOP in Java.