Ternary Operator in Java with Examples: Ternary Operator vs. if...else Statement

Ternary Operator in Java with Examples: Ternary Operator vs. if...else Statement

07 Sep 2024
Beginner
3.35K Views
14 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate (2024)

Ternary Operator in Java

Ternary Operator in Java takes three operands, evaluates the condition, and returns the result. It is also known as the conditional operator.

In this Java Tutorial, we'll explore the syntax along with practical examples and advantages of the Ternary Operator. We'll also understand the ternary operator vs. if...else statement in Java Take your coding skills to the next level with our Java Full Stack Developer Certification Training—join the program now!

What is a Ternary Operator in Java?

In Java, the ternary operator, also known as the conditional operator, is a shorthand way of writing an if-else statement. It makes code more concise and readable by evaluating a Boolean expression and returning one of two values based on the evaluation result.

What is a Ternary Operator in Java?

Syntax of Ternary Operator in Java

Variable = Condition ? Expression1 : Expression2
  • Condition: It denotes the condition specified in an if statement.
  • Expression1: If the condition is met, this expression will be saved in the Variable.
  • Expression2: If the condition is false, this expression will be saved in the variable.
  • It stores the result returned by either expression in a variable.
Read More - Top 50 Java Interview Questions

Flowchart of Ternary Operation

Flowchart of Ternary Operation

Examples Illustrating Ternary Operator in Java

Example 1: Finding the greatest of two numbers

public class TernaryOperatorExample {
    public static void main(String[] args) {
        int x = 10;
        int y = 20;

        int result = (x > y) ? x : y;
        System.out.println("The maximum of " + x + " and " + y + " is: " + result);
    }
}

Explanation

In this specific example, the code determines the maximum value between x and y using the ternary operator and then prints the result to the console. The output on execution in the Java Compiler will be "The maximum of 10 and 20 is: 20," as the value of y (20) is greater than the value of x (10).

Output

The maximum of 10 and 20 is: 20

Example 2: Checking odd/even numbers

public class TernaryOperatorExample {
    public static void main(String[] args) {
        // Given expression: int x = 10; String message = (x % 2 == 0) ? "Even" : "Odd";
        int x = 10;
        int y = 11;
        String message1 = (x % 2 == 0) ? "Even" : "Odd";
        String message2 = (y % 2 == 0) ? "Even" : "Odd";

        // Displaying the result
        System.out.println("Number " + x + " is " + message1);
        System.out.println("Number " + y + " is " + message2);
    }
}  

Explanation

The TernaryOperatorExample class in Java demonstrates the usage of the ternary operator to determine whether a given number is even or odd. The main method initializes two integer variables, x, and y, with values 10 and 11, respectively. It then uses the ternary operator to assign a corresponding message based on whether the number is even or odd.

Output

Number 10 is Even
Number 11 is Odd
Read More - Java Developer Salary In India

Ternary Operator Vs. if...else Statement in Java

The ternary operator may sometimes be used to replace multiple lines of code with a single line. It is often used to replace simple if-else statements. By reducing the length of your program, the ternary operator enhances code readability.


public class DivisibilityCheck {
    public static void main(String[] args) {
        int number = 25

        if (number % 5 == 0) {
            // If divisible, print the following message
            System.out.println("The number " + number + " is divisible by 5.");
        } else {
            // If not divisible, print the following message
            System.out.println("The number " + number + " is not divisible by 5.");
        }
    }
}

The above code checks whether a number is divisible by 5 with the help of an if-else statement.

We can use the ternary operator to perform the same operation.


public class DivisibilityByFive {
    public static void main(String[] args) {
        int number = 25;

        // Using the ternary operator to check if the number is divisible by 5
        String result = (number % 5 == 0) ? "Divisible by 5" : "Not divisible by 5";

        System.out.println("Number " + number + " is " + result);
    }
}

If we compare the above two codes, we can see that the code using the ternary operator looks more readable and short than the one using if-else.

The ternary operator can be used to check any condition using a single if-else statement. However, you can choose what to select.

Use of Ternary Operator in Java

The ternary operator in Java is a concise and powerful tool used for conditional expressions. Its primary purpose is to simplify the syntax of certain if-else statements, making code more compact and often improving readability. Here are some common use cases for the ternary operator in Java:

1. Conditional Assignment

public class TernaryOperatorExample {
    public static void main(String[] args) {
    int number = 15;
    String result = (number > 0) ? "Positive Number" : "Negative Number";
    System.out.println(result);
  }
}

Explanation

This example illustrates how the ternary operator provides a concise way to conditionally assign a value based on a boolean expression, making the code more readable and succinct for simple conditional assignments.

Output

Positive Number    

2. Inline Printing

public class TernaryOperatorExample {
    public static void main(String[] args) {
        int temperature = 25;
        System.out.println("The weather is " + ((temperature > 20) ? "warm" : "cold"));
    }
}

Explanation

By using the ternary operator to determine and print a weather description based on the temperature. The main method initializes an integer variable temperature with a value of 25. The ternary operator is then employed within a System.out.println statement to decide whether the weather is "warm" or "cold" based on the condition (temperature > 20).

Output

The weather is warm

3. Nested Ternary Operators

public class TernaryOperatorExample {
    public static void main(String[] args) {
    int num1 = 5, num2 = 11, num3 = -15;
    int lowest = (num1 <= num2) ? ((num1 <= num3) ? num1 : num3) : ((num2 <= num3) ? num2 : num3);
    System.out.println("Minimum Number: " + lowest);
  }
}  

Explanation

This example in our Java Online Editor demonstrates the use of nested ternary operators to efficiently find the minimum value among three numbers in a single line of code. While nested ternary operators can be powerful, it's important to use them with caution to maintain code readability.

Output

Minimum Number: -15

Advantages of Java Ternary Operator

  • Code Conciseness: Ternary operators reduce the amount of code required for simple conditional assignments.
  • Improved Readability: In certain cases, the ternary operator can make the code more readable, especially when dealing with short conditional expressions.
  • Inline Usage: Ternary operators can be used inline, making code more compact and reducing the need for additional lines.
Read More
Summary

The ternary operator in Java is a powerful tool for simplifying conditional expressions. While it offers conciseness and readability advantages, it should be utilized with caution to maintain code clarity. 

FAQs

Yes, ternary operators can be nested, but it's essential to use parentheses to clarify the order of operations.

In most cases, there is no significant performance difference. The choice between them should be based on code readability and the specific context of usage.

No, the ternary operator is designed for simple binary conditions. For multiple conditions, it's better to use if-else statements.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this