What is the ternary operator?

The ternary operator or well know as a conditional operator is a condensed form of the if-else statement that allows us to test and return some value depending on the given condition. In simple words, a ternary operator is a short form of simple if statement.

Syntax

The ternary operator is the only conditional operator that takes three operands – 

result = <condition> ? <expression 1> :  <expression 2>;

The first operand <condition> must be a boolean expression, the next two operands can be any type of value or expression that returns some value.

If <condition> is true, then the expression 1 is evaluated, otherwise, expression 2 is evaluated.

Example

public class TernaryOperatorExample {

    public static void main(String[] args) {

        // Ternary operator example 1
        int a = 10;
        
        int result = a == 10 ? 20 : 30;
        
        System.out.println("Result : " + result);
        
        // Ternary operator example 2
        String name = "Hello";
        
        name = name.toLowerCase().equals("hello") ? "Hello World" : name;
        
        System.out.println(name);

    }
}

Output

Result : 20
Hello World