break and continue

Keywords break and continue are used to alter the flow of a control structure.

break

Keyword break will suspend subsequent iterations of the loop and transfer the control out of the current loop.

package com.techstackjournal;

public class Break {
	public static void main(String[] args) {

		int[] arr = { 10, 20, 30, 40, 50 };
		int n = 30, index;

		for (index = 0; index < arr.length; index++) {
			if (arr[index] == n) {
				break;
			}
		}

		System.out.println("Found " + n + " at index " + index);

	}
}

break using label

Using label along with break statement we can break outer loop as well. In the below program, outer loop is labeled with name “main” and we breaking it from within inner loop as soon as we found the element in the matrix that we are looking for.

package com.techstackjournal;

public class BreakUsingLabel {
	public static void main(String[] args) {

		int[][] arr = { { 10, 20 }, { 30, 40 }, { 50, 60 } };
		int n = 60, i = 0, j = 0;

		main: for (i = 0; i < arr.length; i++) {
			for (j = 0; j < arr[i].length; j++) {
				if (arr[i][j] == n) {
					break main;
				}
			}
		}

		System.out.println("Found " + n + " at (" + i + "," + j + ")");

	}
}
Found 60 at (2,1)

continue

Keyword continue is a convenient statement to transfer control to next iteration, skipping the ongoing iteration abruptly.

package com.techstackjournal;

public class Continue {
	public static void main(String[] args) {

		int[] arr = { 12, 45, 25, 96, 51 };

		for (int i = 0; i < arr.length; i++) {
			if (arr[i] % 2 == 0) {
				continue;
			}
			System.out.println(arr[i]);
		}
	}
}
45
25
51

Here, we want loop to skip the iteration if the number is even number. So when the array element is even, we are calling out continue, which then skips the rest of the loop and goes back to the next iteration by incrementing i value.

Though we can have the condition as arr[i] % 2 != 0 to print the array element, we chose to use continue here.

As we mentioned earlier, continue statement is convenient for skipping the iteration, but it can be replaced with well written if-else also.

continue using label

Using labels along with continue, you can skip even the outer loop iteration. In the below program, we are skipping the outer loop using label to print only odd rows of matrix.

package com.techstackjournal;

public class ContinueUsingLabel {

	public static void main(String[] args) {

		int[][] arr = { { 10, 20 }, { 30, 40 }, { 50, 60 }, { 70, 80 } };

		main: for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				if (i % 2 == 0) {
					continue main;
				}
				System.out.print(arr[i][j] + " ");
			}
			System.out.println();
		}

	}

}
30 40 
70 80