Skip Top Navigation Bar

Using the Ternary Conditional Operator

What is the Ternary Conditional Operator?

The Ternary Conditional Operator results in a value based on whether a Boolean expression is evaluated to true or false.

The ternary conditional operator consists of a question mark (?) and a colon (:), as follows:

<Boolean expression> ? <expression if true> : <expression if false> 

Ternary Conditional Operator consists of three expressions:

<Boolean expression> ? <expression 1> : <expression 2> 

The first expression is a Boolean expression expression 1 and expression 2 can be any expression:

  • A value
  • A non-void method call
  • Another ternary conditional operator expression

Example 1: Even or Odd

To determine whether x is even or odd, we can use the mod operator to determine whether x is divisible by 2. If the result of x % 2 is 0, then x is even otherwise, it is odd.

Alt Text

To re-write this if statement using ternary conditional operators, we will put the boolean expression in first.

Alt Text

The ? operator is used after the boolean expression. Think of it as asking if the boolean expression is true. If it is true, then the next part of the expression is evaluated and Even is assigned to result.

Alt Text

A colon (:) is used to separate what happens when the boolean expression is true and when it evaluates to false. If the boolean expression evaluates to false in this example, Odd is assigned to result.

Alt Text

To Recap

These two statements are equivalent just written differently.

Produces the same result as:

We could use the ternary conditional operator to print whether the value assigned to x is even or odd simply by putting the expression inside a System.out.println statement:

Example 2: Calling Methods

Consider a class called Calculator that has methods to calculate the sum and positive difference of two values as follows:

public double sum(double value1, double value2);
public double posDifference(double value1, double value2);

Based on a String input of + for sum and +- for positive difference, we can call the appropriate method:

Example 3: Nested Ternary

Expanding on the last example.

Assume Calculator has product and quotient methods as well.

Re-written as an if..else statement:

Ternary and void Method Calls

Remember, when using the Ternary Conditional Operator, the result is a value. You can not use it to call void methods. For example, consider a Robot class that has methods for turning the robot to the left and right as follows:

public void turnRight()
public void turnLeft()

Assuming randy is a properly declared Robot and direction is an int variable, we can NOT write any of the following:

(direction == 39) ? randy.turnRight() : randy.turnLeft();

boolean b = (direction == 39) ? randy.turnRight() : randy.turnLeft();

System.out.println ((direction == 39) 
                     ? randy.turnRight() : randy.turnLeft());

Resources

Calculator - Using Conditionals and Lambda Mini-Lab