break 문
프로그램의 일부를 수행하지 않고 블록 {} 을 빠져나와서 switch 문, for 문, while 문, do while 문 등의 제어를 벗어나기 위해 사용된다.
break 문을 이용한 while 문 빠져나오기
public class Test01 {
public static void main(String[] args) {
int n = 1;
while( n <= 10 ){
System.out.println( n + " Hello World");
n++;
if( n == 5) break; // n값이 5이면 while문 빠져나옴
}
}
}
continue 문
break 문처럼 반복문을 빠져나가는 것이 아니라 continue 문 다음 문장을 실행하지 않고 다시 반복문의 처음으로 돌아간다.
continue 문을 이용한 홀수값 출력
public class Test01 {
public static void main(String[] args) {
for(int i=0 ; i < 10 ; i++){
if( i%2 == 0) continue;
System.out.println("홀수값: " + i);
}
}
}