자바 삼항 연산자
Java 삼항 연산자는 세 개의 피연산자를 사용하는 유일한 조건부 연산자입니다. Java 삼항 연산자는 if-then-else 문을 한 줄로 대체하며 Java 프로그래밍에서 많이 사용됩니다. 아래 예제와 같이 삼항 연산자를 사용하여 스위치를 바꿀 수도 있습니다.
자바 삼항 연산자
package com.journaldev.util;
public class TernaryOperator {
public static void main(String[] args) {
System.out.println(getMinValue(4,10));
System.out.println(getAbsoluteValue(-10));
System.out.println(invertBoolean(true));
String str = "Australia";
String data = str.contains("A") ? "Str contains 'A'" : "Str doesn't contains 'A'";
System.out.println(data);
int i = 10;
switch (i){
case 5:
System.out.println("i=5");
break;
case 10:
System.out.println("i=10");
break;
default:
System.out.println("i is not equal to 5 or 10");
}
System.out.println((i==5) ? "i=5":((i==10) ? "i=10":"i is not equal to 5 or 10"));
}
private static boolean invertBoolean(boolean b) {
return b ? false:true;
}
private static int getAbsoluteValue(int i) {
return i<0 ? -i:i;
}
private static int getMinValue(int i, int j) {
return (i<j) ? i : j;
}
}
위의 삼항 연산자 Java 프로그램의 출력은 다음과 같습니다.
4
10
false
Str contains 'A'
i=10
i=10
보시다시피 if-then-else 및 switch case 문을 피하기 위해 자바 삼항 연산자를 사용하고 있습니다. 이 방법으로 우리는 자바 프로그램의 코드 줄 수를 줄이고 있습니다. 이것이 자바의 삼항 연산자에 대한 빠른 정리를 위한 전부입니다.