Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Ternary Operator in Java

Last Updated on March 2, 2023 by Prepbytes

Ternary Operator in Java provides a shorter and more concise way of implementing simple if-else conditions in a single line. Let us study about this operator in detail. Pre-Requisite for this topic is “If-Else” Conditions in Java. So, we are now starting with the definition and syntax of Ternary Operator in Java.

What is Ternary Operator in Java?

Ternary Operator in Java is a shorthand way of writing if-else conditions in Java. The only conditional operator that accepts three operands is the Java ternary operator. It is a one-liner substitute for the if-then-else statement that is often used in Java programming. We may use the ternary operator instead of if-else conditions, or we can use nested ternary operators to swap conditions. Although it follows the same algorithm as an if-else statement, the conditional operator takes up less space and aids in the writing of if-else statements.

Syntax of Ternary Operator in Java

The above expression will get executed as:

if(Expression1)
{
    variable = Expression2;
}
else
{
    variable = Expression3;
}

Flowchart of Ternary Operator in Java

Here is a simple flowchart, representing the use of Ternary Operator in Java.

If Expression1 is true, then Expression2 will be executed, else Expression3 is executed.

Examples of Ternary Operator in Java

Here are some of the examples of Ternary Operator in Java, which are showing the various uses of Ternary Operator

Example 1: Using Ternary Operator as an alternative to “if-else” Statement in Java
The ternary operator in Java can be used as an alternative to the if-else statement for simple cases. The syntax for using the ternary operator in this way is:

expression ? result1 : result2;

Here, expression is the expression being evaluated, and result1 is the value that will be returned if the expression is true, and result2 is the value that will be returned if the expression is false.

Here is an example of using the ternary operator as an alternative to the if-else statement:

Code:

class Main{
    public static void main (String[] args) {
        int number = 5;
        String message = (number % 2 == 0) ? "Even" : "Odd";
        System.out.println("Number is " + message);
    }
}

Output:

Number is Odd

As you can see, the ternary operator can be used as a compact and concise alternative to the if-else statement.

Example 2: Using Ternary Operator as an alternative to “if-else-if” Statement in Java
The ternary operator in Java can be used as an alternative to the if-else-if statement for simple cases. The syntax for using the ternary operator in this way is:

expression1 == value1 ? result1 : expression1 == value2 ? result2 : expression1 == value3 ? result3 : defaultResult;

Here, expression1 is the expression being evaluated, and value1, value2, value3 are the possible values it can take. result1, result2, result3 are the values that will be returned if the corresponding value is matched, and defaultResult is the value that will be returned if none of the values are matched.

Here is an example of using the ternary operator as an alternative to the if-else-if statement:

Code:

class Main{
    public static void main (String[] args) {
        int score = 75;
        String grade = (score >= 90) ? "A" :
               (score >= 80) ? "B" :
               (score >= 70) ? "C" :
               (score >= 60) ? "D" : "F";
        System.out.println("Grade: " + grade);

    }
}

Output:

Grade: C

As you can see, the ternary operator in java can be used as a compact and concise alternative to the if-else-if statement, but it should only be used for simple cases where the conditions and expressions are relatively straightforward. For complex cases, it is better to use the traditional if-else-if statement to avoid making the code harder to understand and maintain.

Example 3: Using Ternary Operator as an alternative to “Switch-Case” Statement in Java
The ternary operator in Java can be used as an alternative to the switch-case statement for simple cases. The syntax for using the ternary operator in this way is as given below:

expression1 == value1 ? result1 : expression1 == value2 ? result2 : expression1 == value3 ? result3 : defaultResult;

Here, expression1 is the expression being evaluated, and value1, value2, value3 are the possible values it can take. result1, result2, result3 are the values that will be returned if the corresponding value is matched, and defaultResult is the value that will be returned if none of the values are matched.

Here is an example of using the ternary operator as an alternative to a switch-case statement:

Code:

class Main{
    public static void main (String[] args) {
        int dayOfWeek = 5;
        String dayName = (dayOfWeek == 1) ? "Monday" :
                		(dayOfWeek == 2) ? "Tuesday" :
                		(dayOfWeek == 3) ? "Wednesday" :
                		(dayOfWeek == 4) ? "Thursday" :
                		(dayOfWeek == 5) ? "Friday" :
                		(dayOfWeek == 6) ? "Saturday" :
                		(dayOfWeek == 7) ? "Sunday" : "Invalid Day";
        System.out.println("Day: " + dayName);
    }
}

Output:

Day: Friday

As you can see, the ternary operator in java can be used as a compact and concise alternative to the switch-case statement in the above example for displaying the day of the week, but it should only be used for simple cases where the conditions and expressions are relatively straightforward.

Nesting Ternary Operator in Java

In Java, you can nest ternary operators to create more complex conditional expressions. As studied above, A ternary operator in java is a shorthand way of writing an if-else statement, and has the following syntax:

condition ? valueIfTrue : valueIfFalse

To nest ternary operators, you can simply include another ternary operator as the “valueIfTrue” or “valueIfFalse”. Here’s an example of how you could use nested ternary operators to conditionally assign a value to a variable:

int x = 5;
int y = 10;
int z = 20;
int result = x > y ? (x > z ? x : z) : (y > z ? y : z);

In this example, the outer ternary operator compares x and y. If x is greater than y, the inner ternary operator is evaluated, comparing x and z. If x is greater than z, x is assigned to result, otherwise z is assigned. If x is not greater than y, the inner ternary operator is evaluated, comparing y and z. If y is greater than z, y is assigned to result, otherwise z is assigned.

Note: Although, nested ternary operators can be useful in some cases, they can also make code more complex and harder to read. If you find that your code is becoming too complex to understand using nested ternary operators, it may be better to use an if-else statement instead.

Advantages of Ternary Operator in Java

The ternary operator in Java has many advantages, including

  • The ternary operator in Java is a compact and concise way of writing simple “if-else” statements, making the code more readable and reducing its length.
  • By using the ternary operator, you can write conditional statements in a single line, making it easier to understand and maintain the code.
  • Since the ternary operator in java evaluates expressions based on a single condition, it can be faster than if-else statements for simple cases.
  • The ternary operator in java is best suited for simple conditions that return one of two values based on a single condition.

Disadvantages of Ternary Operator in Java

Along with several advantages, the ternary operator in Java also have some disadvantages. These disadvantages are listed below:

  • When used excessively, the ternary operator can make the code harder to read and understand, especially for less experienced developers.
  • The ternary operator in java is not suitable for complex conditions, as it can make the code harder to understand and maintain. In such cases, it is better to use traditional if-else statements.
  • The ternary operator only allows you to evaluate one condition and return one of two values. This can limit its functionality in cases where you need to evaluate multiple conditions or return multiple values.
  • When used improperly, the ternary operator can result in errors, making it important to use it with caution and only for simple conditions.

Conclusion
We learned about the ternary operator in Java in this concise article. It is not viable to use a ternary operator to replace every if-else construct. However, it is a useful tool in particular situations and makes our code lot shorter and more legible.

Leave a Reply

Your email address will not be published. Required fields are marked *