Ternary Operator in Java

Open-a-File-in-Python-Feature-1.jpg

The ternary operator in Java is a concise alternative to the if-else statement, allowing you to evaluate a condition and select one of two values in a single line of code. Whether you are assigning grades, deciding messages, or returning values, this operator keeps your code clean and simple. It is a decision-maker that saves time and space in your programs. In this article, we will discuss how the Java ternary operator works, when to use it, and why it is so important.

Table of Contents:

What is the Ternary Operator in Java?

The ternary operator in Java is a shorthand for simple if-else statements, which allows you to write a conditional expression that returns one of two values depending on whether a condition is true or false, and all in a single line of code.

What is the Ternary Operator in Java

The term ternary means three parts, i.e., it has three operands or parts:

  • boolean condition
  • Expression 1: if the condition is true
  • Expression 2: if the condition is false

The main purpose of the ternary operator is:

  • To simplify decision-making expressions
  • To replace simple if-else blocks
  • To make the code more concise when assigning the values based on the conditions.
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
quiz-icon

Ternary Operator Syntax in Java

The following is the syntax of the ternary operator in Java:

Ternary Operator Syntax in Java
condition ? expression_if_true : expression_if_false

In the above expression:

  • variable stores the result as per the condition, which is true or false
  • condition is a boolean expression that is evaluated first, and its result is true or false
  • ? separates the condition from the true-case expression
  • Expression1 is the value or code that will be used if the condition is true
  • : separates the true-case and false-case expressions
  • Expression2 is the value or code that will be used if the condition is false.

The above expression is equal to the following if-else statement in Java:

if (condition) {
    result = Expression1;
}
else {
    result = Expression2;
}

Flowchart of Ternary Operator

Now, let us discuss the ternary operator with the help of the flowchart.

Flowchart of Java Ternary Operator

The above flowchart explains how the ternary operator works internally when used in a Java program. It starts with checking a condition, shown as Expression 1 at the top of the chart. This expression is a boolean condition, i.e., its result will be either true or false, and based on this result, the flow of execution will proceed in two different directions.

If the condition is true, the flow moves to the right side of the chart, where the ? (question mark) part of the ternary operator is executed, which leads to Expression 2. This expression represents the outcome or value that should be used when the condition is satisfied (i.e., when it is true). This value becomes the result of the ternary expression.

On the other hand, if the condition evaluates to false, the flow shifts to the left side of the flowchart, where the :(colon) part of the ternary operator is executed, leading to Expression 3. This expression is the outcome used when the condition is not met (i.e., when it is false).

Finally, whether the result came from the true or false path, the outcome flows into the Resultant Value of the Expression block. This result is then either stored in a variable or used directly in a print/output statement or another expression. The chart essentially shows how only one of the two possible expressions is selected and used, depending on the condition.

Usage of Ternary Operator in Return Statements

The ternary operator is often used in return statements in the conditional logic. So, instead of using an if-else statement to determine what to return, you can write a single-line return expression that evaluates a condition and returns one of two values, which improves code conciseness when the logic is simple and readable.

Example:

Java

Output:

return

Explanation: In the above Java program, the getGrade() method uses a ternary operator in the return statement to determine the grade based on the score. Every time it checks a range of scores and returns a grade like “A”, “B”, “C”, and so on according to that. The score above is 78, which falls between 70 and 80; hence, the output is Grade: C.

Java Ternary Operator Examples

Now, let us discuss the ternary operator in Java with the help of examples.

1: Find the Largest of Three Numbers

In this example, we will discuss how to find the largest of three numbers using the ternary operator in Java.

Example:

Java

Output:

Java Ternary Operator Example1

Explanation: In the above Java program, first, we find the larger number between a and b. Then we compare the result with c to get the largest overall result. The expression (a > b) ? a : b gives the larger number between a and b. Then, the result from the previous expression is compared with the result of c ? ((a > b) ? a : b) : c, which returns the largest of the three numbers.

2: Perform Arithmetic Operations

In this example, we will discuss how to perform arithmetic operations based on conditions using the ternary operator in Java.

The general syntax of performing the arithmetic operations using the ternary operator is below:

result = (condition) ? (arithmetic_operation_1) : (arithmetic_operation_2);

Example:

Java

Output:

Java Ternary Operator Example2

Explanation: The above Java program uses the ternary operator to decide between two arithmetic operations. It uses the ternary operator to compare the two numbers with the condition (a > b). Since 15 is greater than 10, the condition evaluates to true. As a result, the expression after the question mark (a + b) is executed, which adds the two values and gives 25.

Get 100% Hike!

Master Most in Demand Skills Now!

3: Perform Assignment Operations

In this example, we will discuss how to perform assignment operations based on conditions using the ternary operator in Java.

Java

Output:

EvenOddExample

Explanation: In the above Java program, the ternary operator (num % 2 == 0) ? “Even” : “Odd” checks whether the given number is divisible by 2. If the condition (num % 2 == 0) is true, it returns “Even”; otherwise, it returns “Odd”, and the returned string is directly assigned to the variable result.

4: Using Ternary With Final Keyword

In this example, we will discuss how to use the ternary operator with the final keyword in Java.

Example:

Java

Output:

Java Ternary Operator Example3

Explanation: In the above Java program, the ternary operator (marks >= 40) ? “Pass” : “Fail” checks if the student passed or failed. Since the ternary expression returns one of two string values, it can be used to initialize the final variable directly. After initialization, the result becomes a constant and cannot be changed later.

Nested Ternary Operator in Java

A nested ternary operator means using one ternary operator inside another ternary operator. It allows you to check multiple conditions in a compact way using the ? : syntax. In a nested ternary operator, one or both of the outcomes can contain another ternary operation, i.e.,

condition1 ? (condition2 ? value1 : value2) : value3;

In the above syntax,

  • If condition1 is true, then: condition2 will be evaluated
  • Then, if condition2 is true, it will return value1, Else, it will return value2
  • If condition1 is false, then it will return value3

The above expression of a nested ternary operator is equal to the following if-else statement in Java.

if (condition1) {
    if (condition2) {
        result = value1;
    } else {
        result = value2;
    }
} else {
    result = value3;
}

Now, let us understand the nested ternary operator with the help of an example.

Example:

Java

Output:

Nested Ternary Operator in Java

Explanation: The above Java program finds the grades of the students based on their marks using the nested ternary operator. The first condition checks if marks >= 90. Since 85 is less than 90, it moves to the next condition: marks >= 75. This condition evaluates to true, so the expression immediately returns “B” and skips all other conditions.

When to Use a Ternary Operator in Java?

The ternary operator should be used in the following cases:

  • When You Want to Choose Between Two Values: One of the most common and used situations to use the ternary operator is when you want to select one value out of two based on a single condition, because it is a shortcut to writing a simple if-else block.
  • When You Want to Return a Value Quickly: Another great use of the ternary operator is when you need to return a value directly from a method based on a condition. Instead of using a full if-else block to decide what to return based on the condition, you can use the ternary operator, which makes the decision and returns the result in one line.
  • When You Want to Print a Result Based on a Condition: The ternary operator is also useful when you want to print one of two messages based on a condition, without writing multiple lines of if-else.

When Not to Use a Ternary Operator in Java?

The ternary operator should not be used in the following cases:

  • When the Logic Is Too Complex: If the condition or expressions become long or involve multiple operations, using a ternary operator reduces readability for the user.
  • When Return Type is Different: Both outcomes of a ternary must have compatible types; if it is used with incompatible return types, it will result in a compile-time error.
  • When You Need to Execute Multiple Statements: The ternary operator is an expression, not a statement, it evaluates a condition and returns a value, not a sequence of statements or actions. because of which you can’t include multiple statements.

Ternary Operator vs if-else Statement in Java

Below are the key differences between the Ternary operator and the if-else statement in Java:

Feature Ternary Operator if-else Statement
Syntax condition ? value_if_true : value_if_false; if (condition) { … } else { … }
Type Expression Statement
Length Short and compact Longer
Readability Good for simple conditions Better for complex or multi-step logic
Multiple Statements Support Not supported Fully supported
Beginner Friendly Can be confusing Easier to learn and use
Performance Same Same

Advantages of the Ternary Operator in Java

The ternary operator in Java has the following advantages:

  • The ternary operator helps you write shorter code by replacing multiple if-else blocks with a single-line expression.
  • It makes small decisions easy to understand at once, especially in assignments and return statements.
  • You can use the ternary operator directly while assigning the values to the variables, returning values from methods, and printing the result based on the given condition, which avoids extra variables and blocks.
  • When your logic involves only binary decisions, the ternary operator helps you to eliminate the repetition of if-else statements, which keeps your code clean.
Unlock Your Future in Java
Start Your Java Journey for Free Today
quiz-icon

Conclusion

The ternary operator in Java is a concise and efficient alternative to simple if-else statements, which allows you to assign, return, or print values based on a given condition in a single line. It is ideal for simple and binary decisions, but it should be avoided for complex or multi-step conditions where an if-else has better clarity. You should use the ternary operator to keep your code neat and clean. Understanding when and how to use the ternary operator can effectively enhance your Java programming style.

If you want to learn more about the ternary operator in Java, you can refer to our Java Course.

Java Ternary Operator – FAQs

Q1. What is a ternary operator in Java with 3 conditions?

The ternary operator consists of three operands: a condition, a result for true, and a result for false.

Q2. Is the ternary operator faster than an if-else statement?

The ternary operator is generally not faster than if-else in terms of performance.

Q3. Is the ternary operator right-associative?

Yes, the ternary operator in Java is right-associative because it evaluates the expression from right to left.

Q4. Can we use continue in the ternary operator?

No, you cannot use the continue keyword inside a ternary operator because the continue keyword is a control statement and is only valid inside loops to skip to the next iteration. The ternary operator is an expression, not a control structure.

Q5. What is the nested ternary operator in Java?

A nested ternary operator is an operator used when one ternary operator is placed inside another. It allows you to find multiple conditions in a compact, one-line expression.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner