Ternary Operator in Java

In this lesson of our Java course, we will take a look at the Ternary Operator in Java. The ternary operator in Java is a shorthand way of writing simple if-else statements. It allows developers to condense complex statements into a single line of code, making the code more readable and concise. In this article, we will discuss the syntax of the ternary operator and provide examples of how it can be used in Java.

1. Ternary Operator in Java Syntax

Let’s take a look at the Java Ternary operator:

condition ? expression1 : expression2

Here, condition is evaluated first. If condition is true, expression1 is executed, and if condition is false, expression2 is executed. The value returned by the ternary operator is either expression1 or expression2

Ternary Operator in Java
Ternary Operator in Java

2. Ternary Operator Example

Let’s take a look at the Java ternary operator example for better understanding:

class JavaTernaryOperatorExample {
    
    public static void main(String[] args) {
        int y = (x > 5) ? 100 : 200;
     }
}

In the above example, x > 5 is the condition, and 100 and 200 are the expressions. If x > 5 is true, y will be assigned the value 100, and if x > 5 is false, y will be assigned the value 200.

3. Nested Ternary Operators

Ternary operators can also be nested within each other to create complex statements. Here is an example of a nested ternary operator in Java:

class JavaTernaryOperatorExample {

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int z = (x > 5) ? (y > 10 ? 30 : 40) : 50;
    }
}

In the above example, the first ternary operator checks if x > 5, and if it is true, the nested ternary operator checks if y > 10. If y > 10, z is assigned the value 30, and if y <= 10, z is assigned the value 40. If x <= 5, z is assigned the value 50.

Summary

The ternary operator in Java is a useful tool for simplifying complex if-else statements. It allows developers to write more concise and readable code, and it is particularly useful when assigning values to variables based on conditions. In this article, we discussed the syntax of the ternary operator and provided examples of how it can be used in Java.

Whether you are a beginner or an experienced Java programmer, the ternary operator is a valuable tool to have in your toolkit. As always, the source code for this course is available on our GitHub repository.