Java’s Ternary Operator in Three Minutes

Share this article

Java’s Ternary Operator in Three Minutes

The ternary operator is a form of syntactic sugar for if-then-else statements. It is also known as the conditional operator, which is perhaps a more meaningful name because it evaluates conditions like if does. Provided that the operator is used with care, it can make code more concise without sacrificing readability.

This article requires you to have a solid understanding of how if-statements work in Java.

Ternary Operator

The ternary operator evaluates a condition and chooses one of two branches to execute. Like in many other programming languages, ? and : symbols are used to form it. Other common names you might encounter that refer to the same concept are inline if, ternary if and the conditional operator.

Syntax

The name ternary refers to the fact that the operator takes three operands.

condition ? exprTrue : exprFalse

The condition is a boolean expression that evaluates to either true or false. Both, exprTrue and exprFalse are also expressions but they can evaluate to anything you want them to (except void). If the condition is true, the ternary operator evaluates exprTrue. Otherwise exprFalse is evaluated.

The ternary operator is an expression (like price + 20 for example), which means that once executed, it has a value. And that value needs to be further used, for example by assigning it to a variable or returning from a method, or the expression will not compile.

It’s worth mentioning that the operator is lazy in the sense that only the used expression is evaluated: The ternary operator will not evaluate the unused branch.

Examples

As you can see, the basic structure is very similar to an if-then-else statement but it is condensed to a single line. Let’s have a look at a concrete example. It demonstrates how a simple if-then-else statement can be replaced with a ternary operator.

int price;
if (isPremiumMember()) {
    price = 80;
}
else {
    price = 100;
}

// is equivalent to

int price = isPremiumMember() ? 80 : 100;

The price variable gets a value based on whether the user is a premium member or not. As you can see, the ternary operator is succinct and in this case improves readability.

Since you can use it as an expression, oftentimes it enables you to remove multiple return statements in a method by replacing them with a single expression.

int price() {
    if (isPremiumMember()) {
        return 80;
    }
    else {
        return 100;
    }
}

Can be replaced with

int price() {
    return isPremiumMember() ? 80 : 100;
}

The refactored price method is considerably shorter and as legible as before.

Nesting Multiple Operators

Java allows to nest one conditional operator into another one. Be careful when doing that though. Nested conditional operators can hinder readability.

int amount = 10;
String result = amount <= 2 ? "couple" : amount > 2 && amount < 5 ? "few" : amount <= 5 ? "several" : "many";

Although the example can be improved with formatting, sometimes it’s better to avoid using the ternary operator and go with the plain old if-then-else or switch statement route.

The ternary operator consists of three elements

Summary

You’ve learned that the ternary operator allows you to shorten an if-then-else statement to a single line condition ? exprTrue : exprFalse. If done wisely, it makes the code more concise and improves readability.

Fewer lines of code is not always better, though. It’s easy to overuse the ternary operator and make your code less readable. Use common sense and keep in mind that programs must be written for people to read, and only incidentally for machines to execute. A more readable way to express conditions, particularly if there are many of them, can be the switch statement.

Frequently Asked Questions (FAQs) about Java Ternary Operator

What is the difference between the Java ternary operator and the JavaScript conditional operator?

While both Java and JavaScript have a ternary operator, they are used in slightly different ways. In Java, the ternary operator is a shorthand for an if-else statement and is used to make the code more concise. On the other hand, JavaScript’s conditional operator is more flexible and can be used in more complex expressions. It can also be used as a shorthand for an if-else statement, but it can also be used in assignments and return statements.

Can I use the ternary operator in a loop in Java?

Yes, you can use the ternary operator inside a loop in Java. It can be used to simplify the code and make it more readable. However, it’s important to remember that the ternary operator should only be used when the condition and the two possible outcomes are simple and straightforward. If the condition or the outcomes are complex, it’s better to use an if-else statement for clarity.

How does the ternary operator work with null values in Java?

In Java, the ternary operator can be used with null values. If the condition evaluates to true, the first expression is returned. If the condition evaluates to false, the second expression is returned. If either of these expressions is null, then null is returned. This can be useful in situations where you want to provide a default value if a variable is null.

Can I use the ternary operator with strings in Java?

Yes, the ternary operator can be used with strings in Java. It can be used to choose between two different strings based on a condition. For example, you could use it to choose a greeting based on the time of day.

Can the ternary operator be used in a return statement in Java?

Yes, the ternary operator can be used in a return statement in Java. This can make the code more concise and easier to read. However, it’s important to remember that the ternary operator should only be used when the condition and the two possible outcomes are simple and straightforward. If the condition or the outcomes are complex, it’s better to use an if-else statement for clarity.

Can I use the ternary operator with arrays in Java?

Yes, the ternary operator can be used with arrays in Java. It can be used to choose between two different array elements based on a condition. This can be useful in situations where you want to select an element from an array based on a condition.

Can I use the ternary operator with boolean values in Java?

Yes, the ternary operator can be used with boolean values in Java. It can be used to choose between two different boolean values based on a condition. This can be useful in situations where you want to choose a boolean value based on a condition.

Can I use the ternary operator with objects in Java?

Yes, the ternary operator can be used with objects in Java. It can be used to choose between two different objects based on a condition. This can be useful in situations where you want to choose an object based on a condition.

Can I use the ternary operator with functions in Java?

No, the ternary operator cannot be used with functions in Java. The ternary operator is used to choose between two expressions based on a condition. Functions are not expressions in Java, so they cannot be used with the ternary operator.

Can I use the ternary operator with operators in Java?

Yes, the ternary operator can be used with other operators in Java. It can be used to choose between two different operations based on a condition. This can be useful in situations where you want to perform a different operation based on a condition.

Indrek OtsIndrek Ots
View Author

Software developer, hardware hacker, interested in machine learning, long distance runner.

control flownicolaipquick-tip
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week