Java 삼항 연산자

자바 삼항 연산자

자바 삼항 연산자는 세 개의 피연산자를 사용하는 유일한 조건 연산자입니다. 자바 삼항 연산자는 if-then-else 문의 한 줄짜리 대체로 자주 사용되며 아래 예제에서처럼 switch를 대체하는 데에도 사용될 수 있습니다.

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;
    }
 
}

위 삼항 연산자 자바 프로그램의 출력은:

4
10
false
Str contains 'A'
i=10
i=10

위와 같이 자바 삼항 연산자를 사용하여 if-then-else 및 switch case 문을 피하는 것을 볼 수 있습니다. 이렇게 함으로써 자바 프로그램의 코드 라인 수를 줄일 수 있습니다. 이것으로 자바에서의 삼항 연산자에 대한 간단한 소개를 마치겠습니다.

Source:
https://www.digitalocean.com/community/tutorials/java-ternary-operator