웹사이트 검색

Java break 문, 레이블


Java break 문은 처리 중 루프를 종료하는 데 사용됩니다. 자바 프로그램에서 루프를 벗어나기 위해 break 예비 키워드를 사용합니다.

자바 브레이크

break 문에는 라벨이 없는 것과 라벨이 있는 두 가지 형식이 있습니다. 대부분 break 문은 일부 조건에 따라 루프를 종료하는 데 사용됩니다. 예를 들어 종료 명령에 도달하면 처리를 중단합니다. 레이블이 지정되지 않은 break 문은 해당 문을 포함하는 루프를 종료하는 데 사용되며 switch, for, while 및 do-while 루프와 함께 사용할 수 있습니다.

자바 예제에서 중단

다음은 for 루프, while 루프 및 do-while 루프에서 Java break 문 사용을 보여주는 예입니다.

package com.journaldev.util;

package com.journaldev.util;

public class JavaBreak {

	public static void main(String[] args) {
		String[] arr = { "A", "E", "I", "O", "U" };

		// find O in the array using for loop
		for (int len = 0; len < arr.length; len++) {
			if (arr[len].equals("O")) {
				System.out.println("Array contains 'O' at index: " + len);
				// break the loop as we found what we are looking for
				break;
			}
		}

		// use of break in while loop
		int len = 0;
		while (len < arr.length) {
			if (arr[len].equals("E")) {
				System.out.println("Array contains 'E' at index: " + len);
				// break the while loop as we found what we are looking for
				break;
			}
			len++;
		}

		len = 0;
		// use of break in do-while loop
		do {
			if (arr[len].equals("U")) {
				System.out.println("Array contains 'U' at index: " + len);
				// break the while loop as we found what we are looking for
				break;
			}
			len++;
		} while (len < arr.length);
	}

}

자바 브레이크 라벨

레이블이 지정된 break 문은 외부 루프를 종료하는 데 사용되며 루프가 작동하려면 레이블이 지정되어야 합니다. 다음은 자바 구분 레이블 문 사용법을 보여주는 예입니다.

package com.journaldev.util;

public class JavaBreakLabel {

	public static void main(String[] args) {
		int[][] arr = { { 1, 2 }, { 3, 4 }, { 9, 10 }, { 11, 12 } };
		boolean found = false;
		int row = 0;
		int col = 0;
		// find index of first int greater than 10
		searchint:

		for (row = 0; row < arr.length; row++) {
			for (col = 0; col < arr[row].length; col++) {
				if (arr[row][col] > 10) {
					found = true;
					// using break label to terminate outer statements
					break searchint;
				}
			}
		}
		if (found)
			System.out.println("First int greater than 10 is found at index: [" + row + "," + col + "]");
	}

}