java - if-else와 switch-case의 차이
if-else와 switch-case문의 차이
-
if-else
는 비교 연산 결과인 boolean만 넣을 수 있음 -
switch-case
는 String, int, short, char등의 명확한 값을 넣을 수 있음 -
따라서
switch-case
를 사용할 때는 값이 명확한 선택지가 있을 경우 사용하는게 적절해 보임
조건문의 종류
java에는 두 가지 종류의 조건문이 있다. if-else
조건문 과 switch-case
조건문 이다.
if-else
🗺️ if-else의 형태
if-else
는 아래의 형태로 쓰인다.
if-else
예제문이다. 조건
의 참과 거짓을 통해 코드를 다르게 실행시킬 수 있다.
if-else.java | |
---|---|
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
의 예제문이다. 값
을 통해 코드를 다르게 실행시킬 수 있다.
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).
코드의 가독성으로 값이 명확하다면 switch-case 구문을 사용하는게 적절해 보인다.