Java Ternary Operator a.k.a Conditional Operator

The conditional operator is very similar to the if/else or switch conditional statements and is the only operator in Java that takes three operands. Therefore, conditional operator is also known as ternary operator. This operator not only has three operands but can also be used in variety of ways to make the code more concise. So, we take a deeper than usual look on this operator and present the common usages with examples.

Syntax of ternary operator

Ternary operator always has an associated condition and two expressions – one each for the condition being true or false. The condition expression is the first expression and is separated from the other two operands by a ‘?‘. The two branch operands are separated from each other by a ‘:‘.
The most generic form of the ternary operator can be written as

The control flow first evaluates the condition expression, if the result is true expression_true is evaluated, otherwise expression_false is evaluated.

Note 1: All three operands of ternary operator are expressions and the return value is also an expression. This allows us to nest the ternary operator and do a variety of things such as simulating a switch statement.

Note 2: A method call is also an expression. Therefore, method call can be used as an operand. (See simulating a switch statement and a compound return below)

Note 3:  Parenthesis around the condition expression or around any other operand are completely optional. Java treats everything it encounters before the operator constituents (? and : in this case) as an operand expression.

Control flow of ternary operator

The conditional(ternary) operator is a very concise operator and packs a lot of power. Therefore, it is essential to understand the control flow inside ternary operator. Here are some of the salient points –

  1. The condition expression is always evaluated as the first step in operator evaluation. This is the part that is written before the ‘?‘.
  2. The condition expression must always result in a boolean value. A compile time error is raised if the condition evaluates to anything other than true or false.
  3. Ternary operator is lazy. Therefore, exactly one out of the true and false expressions gets evaluated. Your program must not rely on the execution of both true and false branches for correctness.
  4. The expression_true and expression_false don’t have to be boolean. They can evaluate to any data type such as String, int, float, null etc. anything except void.
  5. All three operators of the ternary operator are expressions, therefore any one or more expression may itself comprise of ternary operator.
  6. The return value of the ternary operator is the value of the expression that gets evaluated. Therefore, it can be any data type.

Examples and Usage Patterns of Ternary Operator

Having looked at the syntax and basic structure of the ternary operator, we now move on to examine the various usage patterns of the operator. These usages are in essence a reuse of the fact that the ternary operator is a conditional operator and can be used to branch the control execution flow.

The following are some of the more common usages of ternary operator –

  1. Replacement for if/else statement
  2. Replacement for switch statement (multiple conditions)
  3. Initialization/assignment of a variable
  4. Making a null check in a single statement
  5. Returning a value in a method call in a single statement

Let’s examine these usages with examples.

Ternary operator as a replacement for if/else statement

This is the most fundamental use of the conditional operator. It can be used to write an if/else statement more concisely.

As an example consider the method below –Java

The method is passed a boolean argument that informs whether the user has won a lottery or not. The single statement inside the method declares the result by printing a suitable message.

Note: There should be at least one else statement. You cannot ‘void’ any operand of the ternary operator. If you have multiple else statements you can go for the nested ternary operator described below.

Ternary Operator for assignment/initialization of variables

This pretty similar to the previous usage pattern, with a difference that the return value of the Ternary operator is captured. This value can be used for initialization or assignment of value to a variable. Although, you can always write a more verbose initialization code based on conditional statements, as shown below, the ternary operator shortens your code.Java

The method calculates salary hike percentage of employees based on whether it’s been a good year or not. The boolean argument to the method is used to determine the hike percentage. If the company is doing good employees get 25% hike else nothing.

Ternary operator for null checking

In Java it is a programming error (which throws a RuntimeException called NullPointerException) to invoke an operation or try to read data from a variable with null value. Therefore, before doing any meaningful operation on a variable we need to check if it is null. One (admittedly, not so popular) way of checking for null is to use ternary operator as follows –Java

Nested ternary operator as a replacement for switch statement or return statement

As noted earlier each operand of the ternary operator is an expression and the return value of the ternary operator is also an expression. By virtue of this fact, we can write a nested ternary operator which is equivalent to a switch statement.

Consider the method below. It receives an integer as an argument and we are required to figure out if the number is less than -100, between -100 & 100 or greater than 100. One way to do this would be to write a switch statement. Or we can write an if/else statement with multiple else parts. But the most concise single liner would be using the nested ternary operator as shown below –Java

The above statement has two ternary operators rolled into one.

The first ternary operator checks for the condition that x > 100. If this condition is true, the return value is the String “Your value ” + x + ” is greater than 100” .

If the above condition is false we check another condition x < -100. Depending on whether this condition is true or false we alter the return string.

Note that the above method also demonstrates that we can directly return the value of ternary operator. This makes the code even more compact, but surely at the cost of readability.

Conclusion

In this article we saw the ternary a.k.a conditional operator and its usage with examples. If you want to run these examples you can use the class below –Java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152public class TernaryOperatorExamples {public static void main(String… CodingRaptor ) {basicTO(true);assignmentShortenedDemo(true);String myStr = null;String name = myStr == null ? “CodingRaptor.com” : myStr;System.out.println(“Example of an ‘inline’ null check ” + name);// a method call is an expression tooboolean x = untrue() ? !untrue()  : untrue() ;System.out.println(“2B || !2B?:” + x);System.out.println(rangeOf(-191));System.out.println(rangeOf(91));System.out.println(rangeOf(191));}private static boolean untrue() {return false;}private static void assignmentShortenedDemo(boolean goodTimes) {boolean isFantasticYear = goodTimes;// the following will not compile, so ternary operator comes handy/** hikePercentage = if(isFantasticYear) 25; else 0;*/int hikePercentage = isFantasticYear ? 25 : 0 ;System.out.println(“Dear lowly employees this year you will be awarded hike percentage of ” + hikePercentage);}private static void basicTO(boolean won) {boolean lotteryWon = won;// the code below will be replaced by a concise ternary operator/*  if(lotteryWon)System.out.println(“Hurray you won the lottery”);   elseSystem.out.println(“Lottery, what lottery?)”;*/System.out.println(lotteryWon ? “Hurray you won the lottery” : “Lottery, what lottery?”) ;}private static String rangeOf(int x) {return x > 100 ? “Your value ” + x + ” is greater than 100″ :(x < -100 ? “Your value ” + x + ” is less than -100″ : “Your value ” + x +” lies somewhere betwn -100 and 100″);}}

The output of the above program is

Leave a comment

Your email address will not be published.