Java ternary operator

The ternary operator is a conditional operator in Java. It is used to evaluate Boolean expressions and assigning the result to a variable, or returning the result of the expression from a method.

The syntax of the ternary operator is as

variable=condition?expression1:expression2

The condition is evaluated and if results to true, the value of expression1 is assigned to the variable else the value expression2 is assigned to the variable.

It is a shorter and leaner alternative to if…else statement.

Example 1

package devsought;

public class TernaryOperatorExample1 {

    public static void main(String... args) {

        int score = 20;

        String comment = score >= 50 ? "Pass" : "Fail";

        System.out.println(comment);    

    }

}

When the above program is run, the output is as below

When the value of score is changed to 50, the output becomes

Explanation:

The condition score >= 50 is evaluated and for value 20, false is returned therefore expression2 with value string “Fail” is stored in the variable comment. For score with value 50, true is returned on the condition evaluation and expression1 with value “Pass” is stored on the variable comment and printed.

 

The alternative to the above ternary operator is the below if…else statement

     String comment;

        if (score >= 50) {

            comment = "Pass";

        } else {

            comment = "Fail";

        }

        System.out.println(comment);

Nested ternary operator

The use of the ternary operator can be complex and may involve the valuation of more than one condition values with each result being further evaluated until all condition ranges are evaluated.

Let us see the this by enhancing example 1 to the below scenario. We want to enhance our Exampe1 as follows.

1.If score is below 0 or greater than 100, that is an invalid score and we output comment "Invalid score".( score < 0 || score > 100 ? "Invalid score" :<expression2>)

2.If score between 0 and 39 comment is "Fail".( <more_conditions_and_expressions_to_the_left> : score >= 0 && score < 40 ? "Fail" :<false_expression_or_another_condition>)

3.If score between 40 and 49 comment is "Average".(<more_conditions_and_expressions_to_the_left>: score >= 40 && score < 50 ? "Average" :<false_expression_or_another_condition>)

4.If score between 50 and 69 comment is "Good".(<more_conditions_and_expressions_to_the_left>: score >= 50 && score < 70 ? "Good" : <false_expression_or_another_condition>)

5.If score between 70 and 84 comment is "Excellent!".(<more_conditions_and_expressions_to_the_left> : score >= 70 && score < 85 ? "Excellent!" : <false_expression_or_another_condition>)

6.If score between 85 and 100 comment is "Super Great!".(<more_conditions_and_expressions_to_the_left> : score >= 70 && score < 85 ? "Excellent!" : "Super Great!";)

The full ternary expression is as below;

score < 0 || score > 100 ? "Invalid score" : score >= 0 && score < 40 ? "Fail" : score >= 40 && score < 50 ? "Average" : score >= 50 && score < 70 ? "Good" : score >= 70 && score < 85 ? "Excellent!" : "Super Great!";

The full program is as below.

Example 2

package devsought;

public class TernaryOperatorExample2 {

    public static void main(String... args) {

        int[] scores = new int[]{-2, 60, 22, 91, 40, 79, 86, 102, 44, 72};

        for (int score : scores) {

            System.out.println("Score =" + score + " ,comment =" + comment(score));          

        }

    }

    private static String comment(int score) {

        return score < 0 || score > 100 ? "Invalid score" : score >= 0 && score < 40 ? "Fail" : score >= 40 && score < 50 ? "Average" : score >= 50 && score < 70 ? "Good" : score >= 70 && score < 85 ? "Excellent!" : "Super Great!";

    }

}

On running the program,the output is as below.

Tip: It is not a good practice to use a complex nested ternary operator as it can at times result in code that is difficult to read and understand. For example in the above Example 2  ,the comment() method can be replaced with a method with if…else statements as below.

private static String withIfElse(int score) {

        if (score < 0 || score > 100) {

            return "Invalid score";

        } else if (score >= 0 && score < 40) {

            return "Fail";

        } else if (score >= 40 && score < 50) {

            return "Average";

        } else if (score >= 50 && score < 70) {

            return "Good";

        } else if (score >= 70 && score < 85) {

            return "Excellent!";

        } else {

            return "Super Great!";

        }

    }

 

For future readability and maintenance of the program ,the if…else alternative is more succinct.

The above codes are available on Github.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.