break and continue are java keywords to skip control flow statements depending on certain condition.
break and continue have 2 forms, labeled and unlabeled
Break
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.
Unlabeled break statement usage
public class BreakTest { public static void main(String[] args) { System.out.print("I: "); for (int i = 1; i <= 5; i++) { if (i == 3){ break; //if condition true, control moves out of loop } System.out.print(i+" "); } } }
OutPut
I: 1 2
labeled break statement usage
refer Exit from nested for loop
Continue
The continue statement skips the current iteration of a for, while , or do-while loop, but a labeled continue statement skips the current iteration of an outer loop marked with the given label.
Unlabeled continue statement usage
package trypkg; public class ContinueTest { public static void main(String[] args) { System.out.print("I: "); for (int i = 1; i <= 5; i++) { if (i == 3){ continue; //if condition true, skips current iteration and moves to next iteration } System.out.print(i+" "); } } }
OutPut:
I: 1 2 4 5
Labeled continue statement usage
public class ContinueTestLabeled { public static void main(String[] args) { int arr[] = {2, 3, 4, 54, 33, 73, 5}; System.out.println("Odd numbers are: "); loop: for(int i=0 ; i<arr.length ; i++){ if(arr[i] % 2 == 0){ continue loop; } System.out.println(arr[i]); } } }
OutPut:
Odd numbers are:
3
33
73
5