Java Ternary Operator   Mar 01, 2014

The Java ternary operator is a way of saying a lot while writing a little. It's essentially a shorthand for if-then-else, and there are some clever ways of using it in your programs.

Below are some examples showing how you might use the ternary operator in Java. The ternary operator allows you to check the condition before the question mark, if it's true then it sets the value to the left of the colon, if false it sets the value to the right of the colon.

Example #1a

This simple class outputs 'Adult' or 'Child' depending on the age of the person created. In the isAdultOrChild() method the test is whether the Person is 18 or older, if that check equates to true then 'Adult' is printed, otherwise 'Child' is printed. Obviously this would need to be named to compile.

Example #1b

This shows an alternative to the isAdultOrChild() method from above using traditional if-then-else logic. This is just to demonstrate how much cleaner the ternary operator is for short lines of code.

Example #2

I've set a variable x to -10 and then I use the ternary operator to fetch the absolute value of variable x. This checks whether x is less than zero, if it is then absoluteValue is set to -x to make it positive, otherwise absoluteValue is set to x. This is exactly how Java's java.lang.Math.abs() gets the absolute value of an integer.

Example #3

Here I've used the ternary operator to manipulate a String based on the value of x. This something you see all the time in user interfaces where the programmer has not catered for the edge case of a single item. It's a small thing but it can make a difference in the perception of a product/application. However, I will concede that in this instance, the readability of the statement suffers when used like this.

The Ternary operator is handy to use as a readable replacement for small if-then-else blocks. However, once the usage gets relatively complicated the readability goes down and it's advantages are diminished.

Tags for this post: