// education

제어문(if, switch), 반복문(for, while), 배열(1D/2D) 및 예외 처리

프로그램의 논리적 실행 제어를 담당하는 조건문/반복문과 연속된 데이터를 묶는 배열(Array), 런타임 예외 대처 기법인 try-catch 예외 처리를 배웁니다.


1. 제어문 & 예외 처리 용어 사전 (Glossary)


2. 2차원 배열과 향상된 for문 실습

public class MatrixArrayExample {
    public static void main(String[] args) {
        // 3행 2열의 2차원 배열 선언 및 초기화
        int[][] scoreMatrix = {
            {90, 85}, // 1행 (학생 1의 국어/영어)
            {78, 92}, // 2행 (학생 2의 국어/영어)
            {95, 100} // 3행 (학생 3의 국어/영어)
        };

        System.out.println("=== [학생별 성적 출력] ===");
        for (int i = 0; i < scoreMatrix.length; i++) {
            int sum = 0;
            for (int j = 0; j < scoreMatrix[i].length; j++) {
                sum += scoreMatrix[i][j];
            }
            double avg = (double) sum / scoreMatrix[i].length;
            System.out.println((i + 1) + "번 학생 - 총점: " + sum + "점 | 평균: " + avg + "점");
        }
    }
}

3. try-catch-finally 예외 처리 실전 패턴

public class TryCatchExample {
    public static void main(String[] args) {
        String[] colors = {"Red", "Green", "Blue"};

        try {
            System.out.println("색상 접근: " + colors[5]); // ArrayIndexOutOfBoundsException 발생!
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("에러: 존재하지 않는 인덱스 접근 경고!");
            System.err.println("상세 예외 메시지: " + e.getMessage());
        } finally {
            System.out.println("finally 블록: 예외 발생 여부와 무관하게 무조건 실행됩니다.");
        }
    }
}

4. 자주 묻는 질문 (Q&A)

Q. switch-case 문에서 break 문을 빼먹으면 어떻게 되나요? A. 조건이 일치하는 case 이하의 다른 case 문들이 break를 만날 때까지 연속 실행되어 버리는 Fall-Through 현상이 발생합니다. 자바 14부터는 yield 문법이 포함된 가독성 높은 Switch Expression을 지원합니다.

← 이전변수, 기본 자료형 및 연산자 완벽 해설 다음 →객체지향 프로그래밍 기초: 클래스, 객체, 메소드