JAVA-Switch Statement Unveiled

세카이·2025년 7월 14일

JAVA

목록 보기
1/1

As a beginner, I used to think that switch statements only execute the code inside the case that matches the condition in the parentheses. However, while studying and playing around in the middle of the class, I realized that my understanding was completely wrong. In Java (and probably in other languages as well), unless a break statement is used, once a matching case is found, the program continues to execute all the subsequent cases until it encounters a break. This behavior is known as fall-through. (I researched with chatGPT ^^)

public void method2() {
        int month;
        int days;
        Scanner scanner = new Scanner(System.in);

        System.out.print("월을 입력해주세요 > ");
        month = scanner.nextInt();

        if (!(month >= 1 && month <= 12)) {
            System.out.println("1월 ~ 12월까지 입력하셔야 합니다.");

            return;
        }

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10,12:
                System.out.printf("%d월은 31일까지입니다.\n", month);
//                break;

            case 4:
            case 6:
            case 9:
            case 11:
                System.out.printf("%d월은 30일까지입니다.\n", month);
                break;

            case 2:
                System.out.printf("%d월은 28일 또는 29일까지입니다.\n", month);
        }
    }

In this switch statement, it's easy to assume that only the matching case block should be executed. For example, if month is 3 and the break under case 10,12 is not commented out, then only the first print is executed which is what the program is inteded to do.

However, if that break is commented out, the program continues executing into the next case blocks until it hits a break. This means that it will also execute the code under case: 4,6,9,11, printing both print statments before next break.

This was pretty shocking to me as I used to think that break was only for performance just to avoid unnecessary checks once the matching case is found. But the truth is, it serves to explicitly stop the execution from falling through the next cases.

Here's another simple example to illustrate:

switch (step) {
	case 1:
    	getInsideTheCar();
    case 2:
    	startTheEngine();
    case 3:
        accelerate();
    break;

In this piece of code, if step is 1, it will not only run getInsideTheCar(), but also startTheEngine() and accelerate() functions. This is because there are no break statements in between. So be very careful when using switch statements, and never omit break unless you intentionally want the fall-through behaviour.

TL;DR: Do not omit break unless you intentionally want fall-through behaviour.

1개의 댓글

comment-user-thumbnail
2025년 7월 25일

우와 영어 잘하시네요

답글 달기