Java FAQ: How do I use the Java ternary operator?
Solution: Java ternary operator examples
Here’s an example of the Java ternary operator being used to assign the minimum (or maximum) value of two variables to a third variable, essentially replacing a Math.min(a,b)
or Math.max(a,b)
method call. This example assigns the minimum of two variables, a
and b
, to a third variable named minVal
:
minVal = (a < b) ? a : b;
In this code, if the variable a
is less than b
, minVal
is assigned the value of a
; otherwise, minVal
is assigned the value of b
. Note that the parentheses in this example are optional, so you can write that same statement like this:
minVal = a < b ? a : b;
I think the parentheses make the code a little easier to read, but again, they’re optional, so use whichever syntax you prefer.
You can take a similar approach to get the absolute value of a number, using code like this:
int absValue = (a < 0) ? -a : a;
General ternary operator syntax
Given those examples, you can probably see that the general syntax of the ternary operator looks like this:
result = testCondition ? trueValue : falseValue
As described in the Oracle documentation (and with a minor change from me), this statement can be read as “If testCondition
is true, assign the value of trueValue
to result
; otherwise, assign the value of falseValue
to result
.”
Here are two more examples that demonstrate this very clearly. To show that all things don’t have to be int
s, here’s an example using a float value:
// result is assigned the value 1.0 float result = true ? 1.0f : 2.0f;
and here’s an example using a String:
// result is assigned the value "Sorry Dude, it's false" String result = false ? "Dude, that was true" : "Sorry Dude, it's false";
As shown in these examples, the testCondition
can either be a simple boolean value, or it can be a statement that evaluates to a boolean value, like the (a < 0)
statement shown earlier.
Finally, here’s one more example I just saw in the source code for an open source project named Abbot:
private static final int subMenuDelay = Platform.isOSX() ? 100 : 0;
More power: Using the ternary operator on the right hand side of a Java statement
As Carl Summers wrote in the comments below, while the ternary operator can at times be a nice replacement for an if/then/else statement, the ternary operator may be at its most useful as an operator on the right hand side of a Java statement. Paraphrasing what Carl wrote:
The “IF (COND) THEN Statement(s) ELSE Statement(s)” construct is, itself, a statement.
The “COND ? Statement : Statement” construct, however, is an expression, and therefore it can sit on the right-hand side (rhs) of an assignment.
Carl then shared the following nice examples. Here’s his first example, where he showed that the ternary operator can be used to avoid replicating a call to a function with a lot of parameters:
myFunc( (COND ? defaultValue : getMyFuncParameter()) );
Next, here’s an example where the conditional operator is embedded into a String
, essentially used to construct the String
properly depending on whether x
is singular or plural:
returnString = "There " + (x > 1 ? " are " + x + " cookies" : "is one cookie") + " in the jar.";
And finally, here’s one more of his examples, showing a similar operation within a String
, this time to print the salutation properly for a person’s gender:
returnString = "Thank you " + (person.isMale() ? "Mr. " : "Ms. ") + person.getLastName() + ".";
(Many thanks to Carl Summers for these comments. He initially shared them as comments below, and I moved them up to this section.)
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Java ternary operator test class
As a final note, here’s the source code for a Java class that I used to test some of the examples shown in this tutorial:
public class JavaTernaryOperatorExamples { /** * Examples using the Java ternary operator * @author alvin alexander, devdaily.com */ public static void main(String[] args) { // min value example int minVal, a=3, b=2; minVal = a < b ? a : b; System.out.println("min = " + minVal); // absolute value example a = -10; int absValue = (a < 0) ? -a : a; System.out.println("abs = " + absValue); // result is assigned the value 1.0 float result = true ? 1.0f : 2.0f; System.out.println("float = " + result); // result is assigned the value "Sorry Dude, it's false" String s = false ? "Dude, that was true" : "Sorry Dude, it's false"; System.out.println(s); // example using the ternary operator on the rhs, in a string int x = 5; String out = "There " + (x > 1 ? " are " + x + " cookies" : "is one cookie") + " in the jar."; System.out.println(out); } }
Discussion
If you’re not familiar with it, the Java ternary operator let's you assign a value to a variable based on a boolean expression — either a boolean field, or a statement that evaluates to a boolean result. At its most basic, the ternary operator, also known as the conditional operator, can be used as an alternative to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right hand side of Java statements.