JS에서 이미 반복문을 배웠었어서 굉장히 쉽게 배울 수 있었는데요. 이래서 언어 하나만 하면 좀 수월하게 배우게 된다는거였구나 싶더라고요. 하지만 처음 접하는 do-while문이 있어서 정리를 해보았습니다.

Java 세상에서 일하는 🤖 로봇이 있다고 상상해 봅시다. 이 로봇에게 10번 "Hello!"라고 인사를 시켜봅시다. 그렇다면 로봇에게 어떻게 명령해야 할까요?
System.out.println("Hello!");
System.out.println("Hello!");
System.out.println("Hello!");
System.out.println("Hello!");
System.out.println("Hello!");
// ... 너무 작성하기 힘들지 않으세요?
너무 비효율적이죠? 10번 정도야 괜찮지만 100번, 1000번이면 어떻게 해야 할까요? 일정한 형태의 작업을 반복적으로 수행해야 할 때 필요한 것이 바로 반복문입니다. 반복문을 사용하면 단 한 줄로 해결 가능합니다.
for (int i = 1; i <= 10; i++) {
System.out.println("Hello!");
}
for 반복문에서는 반복 작업을 시작하기 전에 종결 조건을 확인합니다. 종결 조건이 true일 경우 반복을 수행하고, false이면 반복을 끝냅니다.
for (시작조건; 종결조건; 조건변화수식) {
...
}
예제 코드:
for (int i = 1; i <= 10; i++) {
System.out.println("Hello!");
}
반복 횟수와 변수 i의 값
| 반복 횟수 | i의 값 |
|---|---|
| 1회 | 1 |
| 2회 | 2 |
| 3회 | 3 |
| 4회 | 4 |
| 5회 | 5 |
| 6회 | 6 |
| 7회 | 7 |
| 8회 | 8 |
| 9회 | 9 |
| 10회 | 10 |
로봇을 통해 손님들에게 인사를 시켜봅시다.
public class Robot {
public static void main(String[] args) {
int customers = 5;
for (int i = 1; i <= customers; i++) {
System.out.println(i + "th customer, Hello!");
}
}
}
break 문은 탈출 버튼입니다. 반복을 벗어나야 할 때 사용합니다. 손님이 아무리 많이 오더라도 3명의 손님까지만 환대할 예정이라면 break를 활용할 수 있습니다.
public class Robot {
public static void main(String[] args) {
int customers = 5;
for (int i = 1; i <= customers; i++) {
if (i == 4) {
break; // (1) 반복을 벗어납니다.
}
System.out.println(i + "th customer, Hello!");
}
System.out.println("Loop has ended.");
}
}
출력 예시:
1th customer, Hello!
2th customer, Hello!
3th customer, Hello!
Loop has ended.
i == 4일 때 break가 진행되므로 4번째 손님부터는 출력되지 않습니다.
continue 문은 특정 회차의 반복을 건너뛰고(skip) 다음 반복을 진행할 때 사용됩니다. 2번째 손님에게 인사하고 싶지 않을 때 continue를 활용할 수 있습니다.
public class Robot {
public static void main(String[] args) {
int customers = 5;
for (int i = 1; i <= customers; i++) {
if (i == 2) {
continue; // (1) 특정 반복을 건너뜁니다.
}
System.out.println(i + "th customer, Hello!");
}
System.out.println("Loop has ended.");
}
}
출력 예시:
1th customer, Hello!
3th customer, Hello!
4th customer, Hello!
5th customer, Hello!
Loop has ended.
2번째 손님은 건너뛰었기 때문에 출력되지 않습니다.
while 반복문은 종결 조건만 가지고 있습니다. 종결 조건식이 true일 때 반복합니다.
while (종결조건) {
반복할 명령문;
}
예제 코드:
int i = 1;
while (i <= 10) {
System.out.println("i is less than 10.");
i++; // ✅ 없을 경우 무한 루프 발생
}
do-while은 while 문과 비슷하지만 종결 조건을 반복 전이 아니라 후에 체크한다는 점이 다릅니다.
do {
반복할 명령문;
} while (종결 조건);
예제 코드:
int i = 1;
do {
System.out.println("Hello!");
i++;
} while (i <= 10);