switch(1) {
case(1):
System.out.println("Switch(1)");
System.out.println("one");
case(2):
System.out.println("Switch(2)");
System.out.println("two");
case(3):
System.out.println("Switch(3)");
System.out.println("theree");
}
출력값
Switch(1)
one
Switch(2)
two
Switch(3)
three
switch(2) {
case(1):
System.out.println("Switch(1)");
System.out.println("one");
case(2):
System.out.println("Switch(2)");
System.out.println("two");
case(3):
System.out.println("Switch(3)");
System.out.println("theree");
}
출력값
Switch(2)
two
Switch(3)
three
switch(3) {
case(1):
System.out.println("Switch(1)");
System.out.println("one");
case(2):
System.out.println("Switch(2)");
System.out.println("two");
case(3):
System.out.println("Switch(3)");
System.out.println("theree");
}
출력값
Switch(3)
three
switch(1) {
case(1):
System.out.println("Switch(1)");
System.out.println("one");
**break;**
case(2):
System.out.println("Switch(2)");
System.out.println("two");
case(3):
System.out.println("Switch(3)");
System.out.println("theree");
}
출력값
Switch(1)
one
switch(2) {
case(1):
System.out.println("Switch(1)");
System.out.println("one");
**break;**
case(2):
System.out.println("Switch(2)");
System.out.println("two");
**break;**
case(3):
System.out.println("Switch(3)");
System.out.println("theree");
}
출력값
Switch(1)
two
break를 만나면 switch 문의 실행이 즉시 중지된다. 따라서 위의 코드는 아래와 같이 if문으로 변경 할 수 있다.
int i = 1;
if ( i == 1 ) {
System.out.println("Switch(1)");
System.out.println("one");
} else if ( i == 2 ) {
System.out.println("Switch(2)");
System.out.prinln("two");
} else if ( i == 3 ) {
System.out.println("Switch(3)");
System.out.println("three");
}
출력값
Switch(1)
one
switch(4) {
case(1):
System.out.println("Switch(1)");
System.out.println("one");
**break;**
case(2):
System.out.println("Switch(2)");
System.out.println("two");
**break;**
case(3):
System.out.println("Switch(3)");
System.out.println("theree");
**default :**
System.out.println("default");
}
출력값
**default**
switch() 안에 주어진 case가 없는 경우 default 문이 실행된다는 것을 알 수 있다.
<aside> 💡 switch 문을 사용할 때 한가지 주의 할 것은 switch의 조건으로는 몇가지 제한된 데이터 타입만을 사용할 수 있다. byte, short, char, int, enum, String, Character, Byte, Short, Integer
</aside>