Java switch와 conditional statement(조건문) if, if-else, else-if

습토리·2025년 2월 24일
0

Java

목록 보기
20/32

목표

  • 조건문(if, if-else, else-if)이 무엇인지 학습합니다.
  • switch 문이 무엇인지 학습합니다.

---

학습 키워드 점검

  • if - 조건 수식이 참일 때 실행
  • if-else - 조건 수식이 거짓일 때 실행
  • else-if - 여러 개의 조건을 제어할 때 활용
  • switch - 특정 값에 따라 여러 동작을 실행

조건문

조건문을 왜 배워야 하나요?

컴퓨터는 스스로 판단할 수 없습니다. 하지만 미리 정의된 조건을 활용하면 프로그램이 특정 조건에 맞게 동작할 수 있습니다. 예를 들어, 신호등을 보고 우리가 행동을 결정하는 것처럼, 프로그램도 특정 조건에 따라 다르게 동작하도록 만들 수 있습니다.


조건문 구조

조건 수식 부분이 참(true) 혹은 거짓(false) 인지에 따라 명령문 실행 여부가 결정됩니다.

if 문 구조

if (조건수식) {
    // 실행할까? 말까?
    명령문;
}

참일 경우 실행

if (1 < 2) { // true
    System.out.println("This statement will execute.");
}

거짓일 경우 실행하지 않음

if (2 < 1) { // false
    System.out.println("This statement will not execute.");
}

if, if-else, else-if

if

조건이 참일 때만 실행됩니다.

public class Main {
    public static void main(String[] args) {
        String light = "green";

        if (light.equals("green")) {
            System.out.println("Go!");
        }
    }
}

if-else

조건이 거짓일 때 실행할 코드 추가

public class Main {
    public static void main(String[] args) {
        String light = "red";

        if (light.equals("green")) {
            System.out.println("Go!");
        } else {
            System.out.println("Stop!");
        }
    }
}

else-if

여러 개의 조건을 처리할 때 사용됩니다.

public class Main {
    public static void main(String[] args) {
        String light = "yellow";

        if (light.equals("green")) {
            System.out.println("Go!");
        } else if (light.equals("yellow")) {
            System.out.println("Caution!");
        } else {
            System.out.println("Stop!");
        }
    }
}

실행 흐름

  • light = "green"Go!
  • light = "yellow"Caution!
  • light = "red"Stop!

switch

switch 문은 값에 따라 여러 동작을 실행할 때 사용됩니다. 괄호 안에 단일 값만 들어갈 수 있으며, 조건식은 사용할 수 없습니다.

switch 문 구조

switch (단일값) {
    case1:
        // 값1일 때 실행할 코드
        break;
    case2:
        // 값2일 때 실행할 코드
        break;
    default:
        // 위 값들과 일치하지 않을 때 실행할 코드
}

switch 문 예제

public class SwitchNumber {
    public static void main(String[] args) {
        int number = 1;

        switch (number) {
            case 1:
                System.out.println("Number is 1.");
                break;
            case 2:
                System.out.println("Number is 2.");
                break;
            default:
                System.out.println("Number is neither 1 nor 2.");
        }
    }
}

fall-through 현상 주의

break 문을 생략하면 다음 case 문이 실행될 수 있습니다.

public class SwitchNumber {
    public static void main(String[] args) {
        int number = 1;

        switch (number) {
            case 1:
                System.out.println("Number is 1.");
                // break; 확인해보세요!
            case 2:
                System.out.println("Number is 2.");
                break;
            default:
                System.out.println("Number is neither 1 nor 2.");
        }
    }
}

실행 결과 (break가 없을 경우)

Number is 1.
Number is 2.

이처럼 break 문을 사용하지 않으면 다음 case 문까지 실행되는 현상(fall-through)이 발생할 수 있으므로 주의해야 합니다.


이제 조건문을 활용하여 프로그램의 선택지를 만들어 보세요! 🚀

profile
재미난 삶을 살다

0개의 댓글