자바/자바 기초

자바 제어문 완벽 정리 - 조건문, 반복문, break & continue

끄적인다 2025. 4. 13. 01:51
반응형

1. 제어문(Control Statements)이란?

제어문은 프로그램의 실행 흐름을 제어하는 구문으로, 특정 조건에 따라 코드 실행을 분기하거나 반복 수행할 수 있습니다. 자바에서 제어문은 크게 **조건문(Conditional Statements)**과 **반복문(Loop Statements)**으로 나뉘며, 실행 흐름을 제어하는 break & continue 문도 포함됩니다.

제어문 유형설명

조건문 특정 조건에 따라 코드 실행을 결정함 (if, switch)
반복문 특정 조건이 충족될 때까지 반복 실행 (for, while, do-while)
흐름 제어 반복문에서 실행 흐름을 조절 (break, continue)

이제 각각을 자세히 살펴보겠습니다!


2. 조건문 (Conditional Statements)

조건문은 특정 조건에 따라 실행할 코드 블록을 결정할 때 사용됩니다.

📌 if 문

if 문은 주어진 조건이 true일 때만 실행됩니다.

public class IfExample {
    public static void main(String[] args) {
        int num = 10;
        
        if (num > 0) {
            System.out.println("양수입니다.");
        }
    }
}

📌 if-else 문

조건이 false일 때 실행할 블록을 추가할 수 있습니다.

public class IfElseExample {
    public static void main(String[] args) {
        int num = -5;
        
        if (num > 0) {
            System.out.println("양수입니다.");
        } else {
            System.out.println("음수입니다.");
        }
    }
}

📌 if-else if-else 문

여러 개의 조건을 검사하고, 첫 번째 true 조건을 실행합니다.

public class ElseIfExample {
    public static void main(String[] args) {
        int score = 85;
        
        if (score >= 90) {
            System.out.println("A 학점");
        } else if (score >= 80) {
            System.out.println("B 학점");
        } else {
            System.out.println("C 학점");
        }
    }
}

📌 switch 문

switch 문은 하나의 변수 값을 여러 값과 비교하여 실행할 블록을 결정합니다.

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;
        
        switch (day) {
            case 1:
                System.out.println("월요일");
                break;
            case 2:
                System.out.println("화요일");
                break;
            case 3:
                System.out.println("수요일");
                break;
            default:
                System.out.println("알 수 없는 요일");
        }
    }
}

💡 주의: switch 문에서는 break를 사용하지 않으면 다음 case 문도 실행됩니다.


3. 반복문 (Loop Statements)

반복문은 특정 조건이 충족될 때까지 코드 블록을 반복 실행할 때 사용됩니다.

📌 for 문

반복 횟수가 명확할 때 사용합니다.

public class ForExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("현재 숫자: " + i);
        }
    }
}

📌 while 문

조건이 true인 동안 반복 실행됩니다.

public class WhileExample {
    public static void main(String[] args) {
        int count = 0;
        
        while (count < 5) {
            System.out.println("카운트: " + count);
            count++;
        }
    }
}

📌 do-while 문

조건과 상관없이 최소 한 번 실행된 후 조건을 검사합니다.

public class DoWhileExample {
    public static void main(String[] args) {
        int num = 5;
        
        do {
            System.out.println("현재 숫자: " + num);
            num--;
        } while (num > 0);
    }
}

4. break & continue

breakcontinue는 반복문의 실행 흐름을 제어하는 데 사용됩니다.

📌 break 문

break는 반복문을 즉시 종료합니다.

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break; // 5에서 반복 종료
            }
            System.out.println("현재 숫자: " + i);
        }
    }
}

📌 continue 문

continue현재 반복을 건너뛰고 다음 반복을 실행합니다.

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue; // 3을 건너뜀
            }
            System.out.println("현재 숫자: " + i);
        }
    }
}

5. 결론

자바에서 제어문은 프로그램의 흐름을 조작하는 핵심 요소입니다.

조건문: if, if-else, switch를 활용하여 코드 실행을 분기합니다. ✅ 반복문: for, while, do-while을 사용하여 반복 작업을 수행합니다. ✅ break & continue: 반복문을 조절하여 특정 조건에서 종료하거나 건너뛸 수 있습니다.

제어문을 잘 활용하면 가독성 높은 코드를 작성할 수 있으니, 다양한 예제와 함께 연습해보세요! 🚀

반응형