재미있는 코드들
[JAVA] 나만 모르는 삼항 연산자!
tongnamuu
2022. 5. 2. 22:25
일반적으로 우리가 아는 3항 연산자는 이렇게 씁니다.
boolean condition = 4 > 3;
int x = condition ? 5 : 0;
일부 글에서 3항 연산자가
boolean condition = 4 > 3;
int x;
if(condition) {
x = 5;
} else {
x = 0;
}
이렇게 if else 로 바꿀 수 있다고 하는데....
우선 동작에 대해 조금 더 살펴보자!
(좋은 글에서는 expression 과 statement 로 차이를 두기도 한다. 그런데 이 글의 요지는 그게 아니니까 따로 찾아보자.)
결론부터 말하면 3항 연산자와 if else 는 대부분의 경우는 동일하게 동작하지만 항상 동일하게 동작하지는 않는다!
코드로 알아봅시다!
public class Application {
public static void main(String[] args) {
boolean condition = true;
Number x = condition ? 5 : 0.0;
Number y;
if(condition) {
y = 5;
} else {
y = 0.0;
}
System.out.println(x);
System.out.println(y);
}
}
이 코드의 결과를 예측해봅시다!
맞추셨다면 그대로 끄기를 누르시면 됩니다.
못믿겠으면 직접 돌려보시구요.
틀리셨으면 아래글도 읽어보세요!
5가 처음부터 double 형으로 인식된게 아닌가 하는 의심이 들 수도 있으니 코드를 수정해보자
public class Application {
public static void main(String[] args) {
boolean condition = true;
Integer a = 5;
Double b = 0.0;
Number x = condition ? a : b;
Number y;
if (condition) {
y = a;
} else {
y = b;
}
System.out.println(x);
System.out.println(y);
}
}
Integer 과 Double 객체로 명시했음에도
결과는 여전히
5.0, 5 입니다.
즉 삼항연산자와 if else 는 동일하게 동작하지 않을 수도 있다는 것입니다.
다들 명심하세요!
두 번째 상황을 살펴보자!
public class Application {
public static void main(String[] args) {
boolean condition = true;
Integer a = null;
Double b = 0.0;
Object x;
if (condition) {
x = a;
} else {
x = b;
}
System.out.println(x);
}
}
이 경우는 null 이 잘 찍힙니다.
public class Application {
public static void main(String[] args) {
try {
boolean condition = true;
Integer a = null;
Double b = 0.0;
Number x = condition ? a : b;
System.out.println(x);
} catch(Exception e) {
e.printStackTrace();
}
}
}
반면 이렇게 exception 을 찍어보면 NullPointerException 이 발생합니다.
null 과 쓸 때는 주의합시다!
세 번째로 타입이 같다면 어떻게 될까?
public class Application {
public static void main(String[] args) {
try {
boolean condition = true;
Double a = null;
Double b = 0.0;
Double x = condition ? a : b;
System.out.println(x);
} catch(Exception e) {
e.printStackTrace();
}
}
}
이 경우는 null 이다.
public class Application {
public static void main(String[] args) {
boolean condition = true;
Double a = null;
Double b = 0.0;
Double x;
if (condition) {
x = a;
} else {
x = b;
}
System.out.println(x);
}
}
이건 둘 다 null 이 찍힙니다.
오늘의 결론!
무턱대고 삼항 연산자가 if else 와 똑같이 동작한다고 하는일은 없도록 하자!