Ternary Operator in Java

Ternary Operator in Java

12 Apr 2024
Beginner
591 Views
11 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Ternary Operator in Java: An Overview

Ternary Operator in Java takes three operands, evaluates the condition, and returns the result. In this Java Tutorial, we'll explore the syntax, providing a comprehensive overview along with practical examples of the Ternary Operator. To further enhance your understanding and application of ternary operator's concepts, consider enrolling in the best Java Certification Course, to gain knowledge about the effective utilization of unary operators for improved problem-solving and time management.

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 is used to make code more concise and readable by evaluating a Boolean expression and returning one of two values based on the result of the evaluation. The ternary operator has the following syntax:

What is a Ternary Operator in Java?

Syntax:

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

Example of Ternary Operators in Java

Example 1:
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:

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

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 If-else statement

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 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. To learn about operators in Java and Java concepts you can refer Java online tutorial.

FAQs

Q1. Can the ternary operator be nested?

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

Q2. Are there any performance differences between the ternary operator and if-else statements?

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.

Q3. Can the ternary operator handle multiple conditions?

No, the ternary operator is designed for simple binary conditions. For multiple conditions, it's better to use if-else statements.
Share Article
Batches Schedule
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 8th time in a row (2016-2023). 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.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this