Java

[Java] 생활코딩 | 조건문 switch, default

kyra 2022. 9. 11. 14:02

https://youtu.be/0JCmfGsJGEY

Switch

  • 조건문의 대표적인 문법은 if문이지만 조건이 많다면 switch문이 로직을 명료하게 보여줄 수 있다.
  • switch문은 switch 뒤의 괄호 안의 숫자와 일치하는 case로직 이후의 모든 case가 실행된다.
package org.opentutorials.javatutorials.condition;
 
public class SwitchDemo {
 
    public static void main(String[] args) {
         
        System.out.println("switch(1)");
        switch(1){  //괄호 안의 숫자가 1이므로 case1과 그 이후의 모든 로직이 실행
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }
         
        System.out.println("switch(2)");
        switch(2){  //괄호 안의 숫자가 2이므로 case1은 넘어가고 case2와 그 이후 로직 실행
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }
         
        System.out.println("switch(3)");
        switch(3){  //괄호 안의 숫자가 3이므로 case 1, 2는 넘어가고 case 3만 실행
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }
 
    }
 
}

 

위의 코드 실행 결과는 다음과 같다.

 

switch(1)
one
two
three
switch(2)
two
three
switch(3)
three

 

 

  • 만약 switch(1)에서 case1만 실행하고 싶을 때는 break를 사용한다.
public class SwitchDemo {
 
    public static void main(String[] args) {
         
        System.out.println("switch(1)");
        switch(1){
        case 1:
            System.out.println("one");
            break;  //switch 괄호 안의 숫자가 1이므로 case1 실행, break가 있으면 switch문을 빠져나온다.
        case 2:
            System.out.println("two");
            break;
        case 3:
            System.out.println("three");
            break;
        }
        
 //결과는
switch(1)
one

 

  • if문과 switch문은 서로 대체 가능하다.
package org.opentutorials.javatutorials.condition;
 
public class SwitchDemo2 {
 
    public static void main(String[] args) {
         
        int val = 1;
        if(val == 1){
            System.out.println("one");
        } else if(val == 2){
            System.out.println("two");
        } else if(val == 2){
            System.out.println("three");
        }
 
    }
 
}

위의 코드는 앞의 switch문의 코드와 일치하는 결과를 낸다.

 

Default

  • 주어진 케이스가 없는 경우는 default문이 실행된다.
System.out.println("switch(4)");
        switch(4){
        case 1:
            System.out.println("one");
            break;
        case 2:
            System.out.println("two");
            break;
        case 3:
            System.out.println("three");
            break;
        default:
            System.out.println("default");
            break;

위의 코드에서 switch괄호 안 숫자는 4인데 case 4가 존재하지 않으므로, default문이 실행되어 default가 출력된다.