In this article, we’ll go through what the Ternary Operator is in Java and how it works.
1. What is Ternary Operator in Java?
The ternary operator is the ?
followed by 2 :
and it can be used to assign a value to a variable based on the truthiness of a condition. The syntax of the ternary operator is the following:
Object_type_or_primitive variable_name = boolean_value ? value_if_boolean_true : value_if_boolean_false;
Of course, you can use it not only in assignments but when returning a value as it is shown below:
return boolean_value ? value_if_boolean_true : value_if_boolean_false;
This means that the value to be returned will be value_if_boolean_true
if boolean_value is true and value_if_boolean_
false if boolean_value is false.
Additionally, the value_if_boolean_true
or value_if_boolean_false
could be the result of another ternary operator calculation as shown below:
return boolean_value ? another_boolean_value ? value_if_another_boolean_value_true : value_if_another_boolean_value_false : value_if_boolean_false;
To completely understand this, the above snippet would be exactly the same as the snippet below:
if(boolean_value){ if(another_boolean_value){ return value_if_another_boolean_value_true; } else { return value_if_another_boolean_value_false; } } else { return value_if_boolean_false; }
Although the ternary operator can make your code very concise, it has some limitations:
- It must always return a value, therefore you wouldn’t be able to convert this if statement to ternary operator statement:
public static int checkNumber(int x){ if (x >= 0){ return x; } else { throw new IllegalArgumentException("The number cannot be negative"); } }
- It might lead to unreadable code if there are a lot of ternary operators inside ternary operators, so you’d better choose if or switch statement.
2. Ternary Operator Example
Let’s say you would like to implement an abs function, which will return the absolute value of a number. You could of course implement it using an if statement, but with the ternary operator, it is just one line of code as shown below:
public static double abs(double x) { return x >= 0 ? x : -x; }
You can also use it in assignments as already stated in the first section:
public static void printPositiveness(int x) { String xString = x >= 0 ? x == 0 ? "x is zero" : "x is greater than zero" : "x is negative"; System.out.println(xString); }
Here we assign the returned value of the ternary operator to the xString variable.
Also, we demonstrated how you can use the ternary operator inside a ternary operator. The flow of the above snippet is the following:
- Is
x
greater than or equal 0?- If yes, is
x
equal to zero?- Then return
"x is zero"
.
- Then return
- If not, then return
"x is greater than zero"
.
- If yes, is
- If not, return
"x is negative"
.
3. Conclusion
By now you should be able to take full advantage of Java Ternary Operator and make your code more concise when possible. You can find the source code on our GitHub page.