Java Ternary Operator
Jakob Jenkov |
The Java ternary operator functions like a simplified Java if statement.
The ternary operator consists of a condition that evaluates to either true
or false
,
plus a value that is returned if the condition is true
and another value that is returned if
the condition is false
. Here is a simple Java ternary operator example:
String case = ... // get this string from somewhere, e.g. a parameter or program arg String name = case.equals("uppercase") ? "JOHN" : "john";
We will dissect this ternary operator example in the rest of this Java ternary operator tutorial.
Java Ternary Operator Video Tutorial
In case you prefer video, I have a video version of this tutorial here:
Ternary Operator Condition
The ternary operator part of the above statement is this part:
case.equals("uppercase") ? "JOHN" : "john"
The condition part of the above ternary operator expression is this part:
case.equals("uppercase")
The condition is a Java expression that evaluates to either true
or false
.
The above condition will evaluate to true
if the case
variable equals
the Java String value uppercase
, and to false
if not.
The condition can be any Java expression that evaluates to a boolean
value, just like
the expressions you can use inside an if
- statement or while
loop.
Ternary Operator Values
The condition part of a ternary operator is followed by a question mark (?
). After the question
mark are the two values the ternary operator can return, separated by a colon (:
). The values
part of the ternary operator shown earlier is:
"JOHN" : "john";
The values part consists of two values. The first value is returned if the condition parts (see above) evaluates
to true
. The second value is returned if the condition part evaluates to false
.
In the example above, if case.equals("uppercase")
evaluates to true
then
the ternary operator expression as a whole returns the String value JOHN
.
If case.equals("uppercase")
evaluates to false
then the ternary operator expression as
a whole returns the String value john
. That means, that the String variable name
will end up having the value JOHN
or john
depending on whether the expression
case.equals("uppercase")
evaluates to true
or false
.
The values returned can be the result of any Java expression that returns a value that can be assigned to the variable at the beginning of the statement. Because the Java variable at the beginning of the ternary operator example at the top of this article is of type String, then the values returned by the values part must be of type String.
Ternary Operator as Null Check
You can use the Java ternary operator as a shorthand for null checks before calling a method on an object. Here is an example:
String value = object != null ? object.getValue() : null;
This is equivalent to, but shorter than this code:
String value = null; if(object != null) { value = object.getValue(); }
As you can see, both of these code examples avoid calling object.getValue()
if the object
reference is null
, but the first code example is a bit shorter and more elegant.
Ternary Operator as Type Check
It is also possible to use the Java ternary operator as a type check. Here is an example of using the Java ternary operator as a type check:
Object theObj = getTheObject(); long value = -1; value = theObj instanceof Integer ? ((Integer) theObj).intValue() : value; value = theObj instanceof Long ? ((Long) theObj).longValue() : value;
private static Object getTheObject() { //return Integer.valueOf(999); return Long.valueOf(123); }
Notice how the example uses two ternary operator statements after each other. The first checks if the object returned by the getTheObject() method is an instance of Integer or Long, and then casts the theObj reference to either Integer or Long, and call either the intValue() or longValue()
Ternary Operator as max Function
You can achieve the same functionality as the
Java Math max() function using a Java ternary operator.
Here is an example of achieving the Math.max()
functionality using a Java ternary operator:
int val1 = 10; int val2 = 20; int max = val1 >= val2 ? val1 : val2;
Notice how the ternary operator conditions checks if the val1
value is larger than or equal to
the val2
value. If it is, the ternary operator returns the val1
value. Else it returns
the val2
value.
Ternary Operator as min Function
The Java ternary operator can also be used to achieve the same effect as the
Java Math min() function. Here is an example of
achieving the Math.min()
functionality using a Java ternary operator:
int val1 = 10; int val2 = 20; int max = val1 <= val2 ? val1 : val2;
Notice how the ternary operator conditions checks if the val1
value is smaller than or equal to
the val2
value. If it is, the ternary operator returns the val1
value. Else it returns
the val2
value.
Ternary Operator as abs Function
The Java ternary operator can also be used to achieve the same effect as the
Java Math abs() function. Here is an example of
achieving the Math.abs()
functionality using a Java ternary operator:
int val1 = 10; int max = val1 >= 0? val1 : -val1;
Notice how the ternary operator conditions checks if the val1
value is larger than or equal to
0. If it is, the ternary operator returns the val1
value. Else it returns
-val1
, which corresponds to negating a negative number, which makes it positive.
Chained Ternary Operators
It is possible to chain more than one Java ternary operator together. You do so by having one of the values returned by the ternary operator be another ternary operator. Here is an example of a chained ternary operator in Java:
String input = ... // get input parameter String from somewhere. int value = input == null ? 0 : input.equals("") ? 0 : Integer.parseInt(input);
Notice how the first ternary operator condition checks if the input String is null
. If so, the
first ternary operator returns 0 immediately. If the input String is not null
, the first ternary
operator returns the value of the second ternary operator. The second ternary operator checks if the
input String is equal to the empty String. If it is, the second ternary operator returns 0 immediately.
If the input String is not equal to the empty String, the second ternary operator returns the value
of Integer.parseInt(input)
.
You can chain and nest Java ternary operators as much as you want, as long as each ternary operator returns a single value, and each ternary operator is used in place of a single value (the Java ternary operator is an expression, and is thus evaluated to a single value).
Of course you could have simplified the above ternary operator example. Instead of chaining the ternary operators you could have combined the two conditions that return 0 into a single condition, like this:
int value = input == null || input.equals("") ? 0 : Integer.parseInt(input);
However, this is only possible because the value null
and empty string both return the same value (0).
Anyways, the point was to show you how to chain the Java ternary operator. That is why the
example was written the way it was.
Tweet | |
Jakob Jenkov |