Core Java

Ternary Operator Java Example

1. Introduction

The word “ternary“, in mathematical terms, is an operation that takes 3 variables and, when combined, produces a single output. In Java, as in other languages such as JavaScript or Python, the ternary, or conditional operator, is the only operator that takes 3 operands and produces a value. In this example we will examine the syntax and the practical use-cases of the Java Ternary Operator.

2. Java Ternary Operator – Syntax

The ternary operator expression is of the form: boolean-expression ? expressionIfTrue : expressionIfFalse. The boolean-expression is any condition or logical statement that can be evaluated to true or false. If the boolean expression evaluates to true, expressionIfTrue is returned by the operator. If it evaluates to false, expressionIfFalse is returned.

3. Ternary Operator Java Examples

In this section we will review some examples for using the ternary operator, including some practical ones. Below is a basic example:

TernaryExample.java

package com.jcg.ternary.example;
import java.util.stream.IntStream;

public class TernaryExample {
    private int ceiling = 100;
    public static boolean isLessThan100(int i) {
        return i <=100 ? true : false;
    }
    public static void main(String[] args ) {
        System.out.println(TernaryExample.isLessThan100(20));
        System.out.println(TernaryExample.isLessThan100(101));
    }
}

Running the above example produces the following output:

true
false

The function isLessThan100 uses the ternary operator to evaluate if an argument is less than 100. If we break down the return statement:

i=100 is the condition to be evaluated. If it evaluates to true, the first part of the expression returns, in this case the boolean value “true” is returned. If the condition evaluates to false, the second part of the expression, “false”, is returned.

We can further expand on this example by using the ternary operator to recreate the behavior of the Java Math.min function:

TernaryLessThanOrEqual.java

package com.jcg.ternary.example;

import java.util.stream.IntStream;

public class TernaryLessThanOrEqual {

        public static int isLessThanOrEqual(int i, int ceiling) {
            return i  System.out.printf("Is %d less than or equal to %d? %d%n",
                            value, maxValue,
                            TernaryLessThanOrEqual.isLessThanOrEqual(value, maxValue))
            );
    }
}

Running the program produces:

Is 5 less than or equal to 10? 5
Is 6 less than or equal to 10? 6
Is 7 less than or equal to 10? 7
Is 8 less than or equal to 10? 8
Is 9 less than or equal to 10? 9
Is 10 less than or equal to 10? 10
Is 11 less than or equal to 10? 10

In the above code we use the ternary operator to evaluate a stream of data, testing whether a value in the stream is less than a maximum value of 10. When 10 or greater is reached in the stream, 10 is returned as the minimum.

The IntStream.range method creates a stream of integers from 5 to 10. Each value in the stream is passed to the forEach method, which in turn passes it and maxValue as arguments to the isLessThanOrEqual method. In this method, the ternary operator is used to test the condition: i = ceiling, where i is the next value in the stream, and ceiling is the maximum value. If the condition i = ceiling evaluates to true, i is returned. If it evaluates to false, then ceiling is returned as the min.

We see in this example how the ternary operator can be used to evaluate each element of data on the stream. Different evaluations could be made for each element as a single-line operation, without the need for more verbose if-else statements.

For example, if we re-write the isLessThanorEqual method using an if-else statement, we would have:

IfElseExample.java

    public static int isLessThanOrEqual(int i, int ceiling) {
        if (i <= ceiling) {
            return i;
        } else {
            return ceiling;
        }
    }

The if-else statement method takes 4 lines of code, as opposed to the ternary operator which only takes one line of code. In our example, if we have to evaluate data on the stream based on several different conditions, using if-else could produce dozens of statement lines, as opposed to a single-line operation for each evaluation. We can even chain ternary operators together, as in the following example where we evaluate whether to apply discounts based on a customer’s total spend:

ChainedTernaryExample.java

public class ChainedTernaryExample {


    public static double setDiscount(double spend, double maxToSpend, double discount) {
        return spend < maxToSpend ? spend : spend == maxToSpend ?
                spend * (1 - discount/3) : spend * (1 - discount);
    }

    public static void main(String[] args ) {

        double discount = .02;

       System.out.printf("Checkout total with the discount applied: %f%n",
                ChainedTernaryExample.setDiscount(55.00, 50.00, discount ));
        System.out.printf("Checkout total with 1/3 of the discount applied: %f%n",
                ChainedTernaryExample.setDiscount(50.00, 50.00, discount ));
        System.out.printf("Checkout total with no discount applied: %f%n",
                ChainedTernaryExample.setDiscount(45.00, 50.00, discount ));
        
    }
}

The setDiscount method above takes 3 arguments. The first argument represents the total amount the customer has spent. The second represents the maximum spend before discounts are applied. The third is the percentage discount to apply if the spend amount meets certain criteria.

The method then uses chained ternary operators to perform it’s evaluation. The first ternary operator’s condition tests whether the spend is less than the maxToSpend. If true, the spend amount is simply returned. No discount is applied. If false, a second ternary operator is used as the return value. The operator condition tests if the spend equals the maxToSpend. If true, a third of the discount is applied, and the operator returns spend * (1 - discount/3). If false, the full amount of the discount is returned: spend * (1 - discount).

Running the program for each condition produces:

Checkout total with the discount applied: 53.900000
Checkout total with 1/3 of the discount applied: 49.666667
Checkout total with no discount applied: 45.000000

Chaining ternary operations together is a powerful way to write complex logical operations without the verbosity that often results in using multiple if-else statements. However, care must be taken when chaining multiple operations together to not produce hard-to-maintain code.

4. Final Thoughts

We have seen how the ternary operator can be used to produce concise code, replacing a multi-line if-else statement in a single line. It can be a useful alternative for cases where if-else can be either difficult or impractical to use, such as the following code that uses a single printf line to format a response based on the size of a value:

ChainedExampleB.java

package com.jcg.ternary.example;

public class ChainedExampleB {

  public static void main(String[] args ) {

        int value = 15;
        System.out.printf(value == 1 ? "Total: %d item" :
                value >= 1 ? "Total: %d items" : "value cannot be less than 1", value);

    }
}
Total: 15 items

Consider the balance between readability and conciseness when using it. Also consider that the ternary operator uses lazy evaluation, where it only evaluates either the second or third operand. If the second operand evaluates to true, the third operand will not be evaluated. Therefore, be careful with operands that have side effects, such as:
value == x? y++ : z++ .

If value equals x, only y++ will be evaluated. z++ will not, which could have unintended consequences wherever z is used in your code.

In summary, consider using a ternary operator if you need to return a value as a result of a conditional operation, or if using an if-else statement would be too difficult or provide unwanted verbosity. In the workplace I often consider using a ternary operator when I’m using logical operations to format strings, or refactoring my code to find opportunities for brevity and clarity. However, I always need to remember the balance between brevity and verbosity, to prevent instances of unreadable code, especially when chaining multiple operators together. If more than two evaluations are needed, consider using an if-else or switch-case statement.

5. Download the Source Code

Download
You can download the full source code of this example here: Ternary Operator Java Example

Last updated on Aug. 22, 2019

Stephen Ferjanec

Stephen graduated from the University at Buffalo, with Bachelor's degrees in Finance and Information Systems. He has worked in the finance industry for over 20 years, developing software applications for accounting, budgeting and forecasting solutions. His most recent projects are developing web and mobile applications in the retail sector, where he is mainly involved with reporting projects using Spring technologies and Angular.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button