언어/Java

switch 조건문

sector 2023. 7. 25. 19:23

public class Condition{    

    public static void main(String []args){

        int a = 3;

        switch(a%2){

            case 1:

                 System.out.println("홀수");

                 break;

            case 0:

                 System.out.println("짝수");

                 break;

        }

-------------------------------------------------------

        int year= 2023;

        int mod = year%12;

        switch(mod){

            case 0:

                 System.out.println("원숭이띠");

                 break;

            case 1:

                 System.out.println("닭띠");

                 break;

            default : // if의 else와 같은 의미

                 System.out.println("그 외의 동물");

        }

    }

}

결과

 

※ switch 문의 괄호에는 정수 타입(byte, char, short, int, long)과 문자열 타입(String) 변수를 사용할 수 있다.

하지만 자바 11버전에서 long은 사용 불가능.