Ternary Operator in Java: What You Need to Know

Creo2 / Shutterstock.com

The ternary operator in Java is a versatile and powerful tool that every programmer should have in their toolkit. In this blog post, we dive deep into its functionality, providing you with a comprehensive understanding of how to use it and when to apply it in your coding endeavors.

What is the Ternary Operator?

In Java, the ternary operator is a useful tool for creating better conditionals andcontrol flowwhile maintaining readability. Using them is an easy way to upgrade a novice s code, making it moreprofessional and maintainable.

For non-coders, you might recognize it as the classic question mark: ?

Ternary operator in action
Ternary operator in action.


How Do You Use It?

This kind of situation is quite common when programming:

String resultMessage;if (number % 2 == 0) {
resultMessage = The number is even. ;
} else {
resultMessage = The number is odd. ;

There s nothing inherently wrong with this code, but there is a more concise way to do this in Java: the ternary operator. Here s how you could use it to rewrite the above snippet:

String resultMessage = (number % 2 == 0) ? The number is even. : The number is odd.

At first glance, this may seem more complicated, but it s quite simple. Let s break it down. The general form of the ternary operator is:

[variable] = [condition] ? [true_expression] : [false_expression]

Essentially, if the condition is true, then you assign the variable to the true expression. Otherwise, the variable is assigned to the false expression. In this case, those true and false expressions are strings.

Use Cases

Null Checks

Let s say you have a piece of code that sets the display name of a user, but it is not guaranteed that a name has been chosen upon logging in. If the chosen name isnull, then you want the display name to be Guest , and the chosen name otherwise. To accomplish this, you may normally write a code snippet similar to:

String displayName;
if (name == null) {
displayName = Guest ;
} else {
displayName = name;

However, as we ve seen already, you can rewrite that code using a ternary operator:

String displayName = (name == null) ? Guest : name;

boolean isEven = (number % 2 == 0) ? true : false;

Which is, of course, a shortened version of this:

boolean isEven;
if (number % 2 == 0) {
isEven = true;
} else {
isEven = false;

However, this is unnecessarily verbose and a common mistake for novices. In reality, you can write a much simpler form:

boolean isEven = (number % 2 == 0);

As you can see, ternary operators are unnecessary here. The expression will be evaluated as aboolean, and you can assign the variable to it directly.

Nested Ternary Operators

Sometimes, more complex logic is required, but the conditions are repetitive. For example, imagine you want to assign a grade based on a student s score:

char grade;
if (score >= 90) {
grade = A ;
} else if (score >= 80) {
grade = B ;
} else if (score >= 70) {
grade = C ;
} else if (score >= 60) {
grade = D ;
} else {
grade = F ;

Aswitch statementwould likely be a more elegant way of doing this, but for our purposes, let s see how you could do it using ternary operators. In certain cases, it can be useful to nest them:

char grade = (score >= 90) ? A : (score >= 80) ? B : (score >= 70) ? C : (score >= 60) ? D : F ;

For each ternary operator, the true expression is a grade, and the false expression is another ternary operator. With more complex logic, nested ternary operators can become messy and hard to follow, but it can make predictable and repetitive tasks more condensed.

The Difference Between If-Else and Ternary Operators

When choosing between using If-Else statements and ternary operators, there are several factors that come into play, and these go beyond the purpose of your code. As aforementioned, when the logic is repetitive, it is okay to use ternary operators, making the code more condensed.

In other cases, where more complex logic and multiple branches are involved, it is much better to use If-Else statements. However, when you are working within a larger codebase that many people have worked on, it is better to follow code guidelines or precedence.

Of course, you can always use ternary operators and if-else statements in the same class. They get along just fine. For example, the following shows the ternary operator is used to determine the smaller number, and the if-else is used to print out a custom message depending on whether the numbers are equal or not. Can you spot the ternary operator?

Ternary and if-else
Ternary operator and if-else coexist in the same class.


Binary Operators vs. Ternary Operators

Throughout the article, you may have been wondering why it is called the ternary operator. In programming, the subjects of an operator are called operands , and binary or ternary refer to the number of these operands, with binary meaning two and ternary meaning three. Most of theoperatorsyou work with are binary, such as addition and checking for equivalency or inequivalence. For example, when you have the expression:

5 == 2

The operands are 5 and 2. And for the ternary operator, the condition, true expression, and false expression serve as the three operands.

Wrapping Up

While not always necessary, the ternary operator is a helpful tool for any programmer. Under the right circumstances, it can be used to condense down repetitive decisions in code, and it can even be nested to represent more complex logic.

Leave a Comment