[Java] 제어문

김선형·2025년 9월 6일

Java

목록 보기
4/27

조건문

if, else if, else

조건에 따라 코드 블록을 선택적으로 실행한다.

public class Main {

    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("Under C");
        }
    }
}
// B

switch

여러 값 중 하나와 일치하는 분기를 선택하여 실행한다.

public class Main {

    public static void main(String[] args) {
        int menu = 2;

        switch (menu) {
            case 1:
                System.out.println("주식 조회");
                break;

            case 2:
                System.out.println("주식 매수");
                break;

            case 3:
                System.out.println("주식 매도");a
                break;

            default:
                System.out.println("유효하지 않은 선택지");
        }
    }
}
// 주식 매수

반복문

for

조건에 따라 정해진 횟수만큼 반복한다.

public class Main {

    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("주식 가격 확인: " + i + "일차");
        }
    }
}
/*
 * 주식 가격 확인: 1일차
 * 주식 가격 확인: 2일차
 * 주식 가격 확인: 3일차
 * 주식 가격 확인: 4일차
 * 주식 가격 확인: 5일차
 */

for-each

배열이나 컬렉션의 모든 요소를 순서대로 반복할 때 사용한다. 인덱스가 없고 순차 접근만 가능하다. 루프 변수에 새 값을 대입해도 원본 배열이나 컬렉션의 요소 참조가 바뀌지 않는다.

public class Main {

    public static void main(String[] args) {
        String[] stocks = {"Stock1", "Stock2", "Stock3"};

        for (String stock : stocks) {
            System.out.println("보유 주식: " + stock);
        }
    }
}
/*
 * 보유 주식: Stock1
 * 보유 주식: Stock2
 * 보유 주식: Stock3
 */

while

조건이 참인 동안 계속 반복한다.

public class Main {

    public static void main(String[] args) {
        int i = 1;

        while (i <= 3) {
            System.out.println("잔고 확인: " + i + "번째");
            i++;
        }
    }
}
/*
 * 잔고 확인: 1번째
 * 잔고 확인: 2번째
 * 잔고 확인: 3번째
 */

do-while

최소 1회는 실행되고 조건이 참인 동안 반복한다.

public class Main {

    public static void main(String[] args) {
        int count = 0;

        do {
            System.out.println("거래 내역 조회 시도: " + count);
            count++;
        } while (count < 2);
    }
}
/*
 * 거래 내역 조회 시도: 0
 * 거래 내역 조회 시도: 1
 */

✏️ Stream API?
컬렉션이나 배열을 선언형 (무엇을 할 것인가) 방식으로 처리할 때 사용하는 라이브러리다. 반복문 대신 함수형 스타일로 데이터를 필터링, 매핑, 정렬, 집계할 수 있어 간결한 코드 작성이 가능하다.

주요 메서드

메서드유형설명
stream()생성컬렉션으로부터 Stream 생성
filter()중간조건에 맞는 요소만 통과
map()중간각 요소를 다른 값으로 변환
sorted()중간정렬
distinct()중간중복 제거
limit(), skip()중간일부 요소 제한 또는 건너뜀
collect()최종결과 수집 (List, Set, Map 등)
forEach()최종각 요소에 대해 작업 수행
count()최종요소 개수 반환
anyMatch() / allMatch() / noneMatch()최종조건 일치 여부 확인
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<String> stocks = Arrays.asList("Apple", "Amazon", "Google", "Microsoft");

        stocks.stream().filter(s -> s.startsWith("A")).forEach(System.out::println);

        List<Integer> prices = Arrays.asList(1000, 2000, 3000);

        double avg = prices.stream().mapToInt(Integer::intValue).average().orElse(0);

        System.out.println("Average Price: " + avg);
    }
}
/*
 * Apple
 * Amazon
 * Average Price: 2000.0
 */

분기문

break

현재 반복문 또는 switch문을 즉시 종료한다.

public class Main {

    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 4) {
                break;
            }
            System.out.println("거래 횟수: " + i);
        }
    }
}
/*
 * 거래 횟수: 1
 * 거래 횟수: 2
 * 거래 횟수: 3
 */

continue

현재 반복을 건너뛰고 다음 반복으로 진행한다.

public class Main {

    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }
            System.out.println("처리 중인 거래 번호: " + i);
        }
    }
}
/*
 * 처리 중인 거래 번호: 1
 * 처리 중인 거래 번호: 2
 * 처리 중인 거래 번호: 4
 * 처리 중인 거래 번호: 5
 */

return

현재 메서드의 실행을 종료하고 값을 반환하거나 단순히 종료한다.

public class Main {

    public static int getBalance() {
        return 100000; // 100000 반환
    }
}

예외 처리

try-catch-finally

예외 발생 시 프로그램이 중단되지 않도록 예외 상황을 처리하기 위한 제어 흐름 구조다.

public class Main {

    public static void main(String[] args) {
        try {
            int[] stocks = { 10, 20 };
            System.out.println(stocks[2]); // 예외 발생
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index Error: " + e.getMessage());
        } finally {
            System.out.println("Exception handling completed.");
        }
    }
}
/*
 * Index Error: Index 2 out of bounds for length 2
 * Exception handling completed.
 */

throw, throws

예외를 발생시키거나 메서드에서 예외가 발생할 수 있음을 명시한다.

public class Main {

    public static void buyStock(int amount) throws Exception {
        if (amount <= 0) {
            throw new Exception("Amount must be bigger than zero.");
        }
        System.out.println("Bought " + amount + " stocks successfully.");
    }

    public static void main(String[] args) {
        try {
            buyStock(10);

            buyStock(0);
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}
/*
 * Bought 10 stocks successfully.
 * Exception: Amount must be bigger than zero.
 */
profile
선형의 비선형적 기록 🐜

0개의 댓글