Skip to content

java - if-else와 switch-case의 차이

if-else와 switch-case문의 차이

  1. if-else는 비교 연산 결과인 boolean만 넣을 수 있음

  2. switch-case는 String, int, short, char등의 명확한 값을 넣을 수 있음

  3. 따라서 switch-case를 사용할 때는 값이 명확한 선택지가 있을 경우 사용하는게 적절해 보임

조건문의 종류

java에는 두 가지 종류의 조건문이 있다. if-else조건문 과 switch-case조건문 이다.

if-else

🗺️ if-else의 형태

if-else 는 아래의 형태로 쓰인다.

if(조건) {

} else if (조건2){

} else { // 조건이 전부 만족하지 않을 경우 아래의 코드를 실행

}

if-else 예제문이다. 조건의 참과 거짓을 통해 코드를 다르게 실행시킬 수 있다.

if-else.java
1
2
3
4
5
6
7
8
int i = 5;


if( i > 5 ){
    System.out.println("i는 5보다 큽니다");
} else {
    system.out.println("i는 5보다 작거나 같습니다");
}

if-else의 특징 - 비교 구문에 논리 연산만 올 수 있음

java는 파이썬과 다르게 if 구문에 boolean 형의 자료만 넣을 수 있다. 비교 연산자로 얻은 결과 값 또한 boolean이기 때문에 비교 연산도 넣을 수 있다.

switch-case

🗺️ switch-case 형태

switch-case는 아래의 형태로 쓰인다.

switch(String 형태의 값 또는 Enum의 값){
    case 값1:
    case 값2:
        break; // switch 문 실행 종료
    case 값3:
    default: // 아무 조건이 안 맞았을때 이 구문 실행
}
switch-case의 예제문이다. 을 통해 코드를 다르게 실행시킬 수 있다.

swithc-case.java
public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

if-else의 특징 - 비교 구문에 값만 올 수 있음

oracle java tutorial에 따르면, switch는 byte, short, int, char 및 String 등 넣을 수 있다고 한다.

switch에 넣을 수 있는 자료형

Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data type. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

출처 - The switch Statement(oracle java tutorials)

코드의 가독성으로 값이 명확하다면 switch-case 구문을 사용하는게 적절해 보인다.

Comments