Break and Continue Example in Java
On this page (10sections)
Introduction
Break And Continue is a classic Java console program that demonstrates the concept with complete source code and sample output. break, continue and return alter the normal flow inside loops and methods.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
The statements break and continue alter the normal control flow of compound statements. The break statement immediately jumps to the end (and out) of the appropriate compound statement. The continue statement immediately jumps to the next iteration (if any) of the appropriate loop.
Syntax
break;
continue;
Break And Continue Example Program
public class BreakAndContinue{
public static void main(String args[]) {
int[] numbers= new int[]{101,102,103,104,105,106,107,108,109,110};
int add = 0;
for(int i=0; i< numbers.length; i++){
System.out.println("iteration: " + i);
if(i == 5){
System.out.println("calling break statement");
break;
}
if(i%2 != 0){
add = add + numbers[i];
System.out.println("calling continue statement");
continue;
}
System.out.println("Last line of loop executed only for even number of iterations: " + numbers[i]);
}
System.out.println("This is outside the loop, sum: " + add);
}
}
Sample Output
iteration: 0
Last line of loop executed only for even number of iterations: 101
iteration: 1
calling continue statement
iteration: 2
Last line of loop executed only for even number of iterations: 103
iteration: 3
calling continue statement
iteration: 4
Last line of loop executed only for even number of iterations: 105
iteration: 5
calling break statement
This is outside the loop, sum: 206
When to use
Use this break and continue example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
int[] numbers= new int[]{101,102,103,104,105,106,107,108,109,110};updates a variable used in the calculation or output. -
int add = 0;updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
-
A
println/printcall writes text to the console — part of the sample output below. -
The
ifstatement runs the nested code only when the condition is true. -
A
println/printcall writes text to the console — part of the sample output below. -
The
ifstatement runs the nested code only when the condition is true.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.