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.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
Output is:
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