Ternary operator

The conditional (ternary) operator is often used as a short form of an if-else statement. This is simply a conditional assignment of a value to a variable. if-then-else, on the other hand, is a flow control.

condition ? expression1 : expression2;

Example: ternary operator

Code Explanation

3Initializes the variable age of type integer with the value 20
4Creates a new variable message of type String
6If age is higher than 18 the string behind the question mark will be displayed. In this case “you can drive”. Otherwise, the string after the double dot is output “you are not allowed to drive a car”
8Outputs the content of the variable message
public class TernaryOperatorExample {
    public static void main(String[] args) {
        int age = 20;
        String message;
        message = age > 18 ? "you can drive" : "you are not allowed to drive a car";
you can drive