switch 문

중급 Java

Jim White

Java Developer

switch란?

  • switch는 if-else와 유사한 목적
    • 조건에 따라 동작 수행
    • 다중 if-then-else를 대체
  • 다중 if-then-else보다 더 간결함
if (bonus == 10000) {
    System.out.println("Let's buy a car!");
} else if (bonus == 5000) {
    System.out.println("Let's take a trip!");
} else if (bonus == 1000) {
    System.out.println("Let's save!");
}
중급 Java

switch 문법

switch (expression) {
    case value1:  // if (expression == value1)
        // statements
    case value2:  // if (expression == value2)
        // statements
    // use as many case statements as needed
}
중급 Java

switch 예시

char direction = 'N';

switch (direction) {
    case 'E':  
        System.out.println("We are headed east.");
    case 'S':  
        System.out.println("We are headed south.");
    case 'W':  
        System.out.println("We are headed west.");
    case 'N':   
        System.out.println("We are headed north."); // This would be printed
}
중급 Java

break

  • Java가 다음 case들로 계속 진행하는 것을 중단
    • break가 없으면, break를 만날 때까지 다음 case의 문도 실행됨
char direction = 'W';

switch (direction) {
    case 'E':
        System.out.println("We are headed east.");
    case 'S':
        System.out.println("We are headed south.");
    case 'W':
        System.out.println("We are headed west."); // This would be printed
    case 'N':
        System.out.println("We are headed north."); // This would also be printed
}
중급 Java

break로 여러 case를 묶을 수 있음:

char direction = 'N';

switch (direction) {
    case 'E':     
    case 'W':  
        System.out.println("We are headed east or west.");
        break;
    case 'S':  
    case 'N':
        System.out.println("We are headed south or north.");
        break;       
}
We are headed south or north.
중급 Java

default

  • 선택적 default 절을 switch 끝에 추가할 수 있음
    • default는 표현식과 비교할 값이 없음
    • 어떤 case도 일치하지 않으면 default의 문이 실행됨
    • default는 switch의 마지막에 와야 함
  • default는 "그 외 모든 값"을 처리함
char direction = 'z';

switch (direction) {
  case 'E':     
  case 'W':  
    System.out.println("To east or west.");
    break;
  case 'S':  
  case 'N':
    System.out.println("To south or north.");
    break; 
  default:
    System.out.println("We are lost.");
}
We are lost.
중급 Java

조건문 vs switch

  • 동일 작업에 조건문을 사용할 수도 있음
  • 모든 데이터 타입에서 동작
char character = 'A';
if (character == 'A') {
    System.out.println("It's A");
} else if (direction =='B') {
    System.out.println("It's B");
} else {
    System.out.println("Unknown");
}
  • switch가 더 읽기 쉬울 수 있음
  • int, byte, short, char, String 등 일부 타입에서만 동작
char character = 'A';
switch (character) {
  case 'A':
    System.out.println("It's A");
    break;
  case 'B':  
    System.out.println("It's B");
    break;
  default:
    System.out.println("Unknown");
}
중급 Java

연습해 봅시다!

중급 Java

Preparing Video For Download...