Ternary Operator in Java

  • Last Updated: October 7, 2023
  • By: javahandson
  • Series
img

Ternary Operator in Java

In this article, we will learn what is a ternary operator in Java with proper examples. If you want to learn about other Java topics you can click the above Java menu or you can click on this link Java topics.

 

The dictionary meaning of ternary is – composed of three parts. Ternary Operator is also known as Conditional Operator. The only possible ternary operator in Java is this conditional operator.

Ternary Operator is denoted by ? :

Ternary Operator operates on 3 operands which is why this operator is known as a ternary operator.

Syntax of the ternary operator

output = expression ? result1 : result2

The expression should return a boolean. If the expression is true then assign result1 to output else assign result2 to output.

Ex. int output = ( 10 < 15 ) ? 25 : 35
Here the expression is true hence the output will be 25.

The behavior of a ternary operator is just like an if-else condition. But the difference is ternary operator is a single programming statement whereas the if-else condition will have multiple statements inside the parenthesis.

Ternary Operator Example

Write a program to check if a given number is even or not

package com.java.handson.operators;

public class TernaryOperator {
    public static void main(String[] args) {

        int number = 6;
        String result = number % 2 == 0 ? "is even" : "is odd";
        System.out.println(number + " : " + result);

        number = 7;
        result = number % 2 == 0 ? "is even" : "is odd";
        System.out.println(number + " : " + result);
    }
}
Output : 
6 : is even
7 : is odd

Nesting of the ternary operator

Nesting of the ternary operator is also possible which means we can add multiple ternary operators within a single statement.

Nested ternary Operator Example

Write a program to check if a given number is divisible by both 2 and 5

package com.java.handson.operators;

public class TernaryOperator {
    public static void main(String[] args) {

        int number = 20;
        String result = number % 2 == 0 ? number % 5 == 0 ? "is even and divisible by 5" :  " is even but not divisible by 5" : "is odd";
        System.out.println(number + " : " + result);

        number = 16;
        result = number % 2 == 0 ? number % 5 == 0 ? "is even and divisible by 5" :  " is even but not divisible by 5" : "is odd";
        System.out.println(number + " : " + result);

        number = 7;
        result = number % 2 == 0 ? number % 5 == 0 ? "is even and divisible by 5" :  " is even but not divisible by 5" : "is odd";
        System.out.println(number + " : " + result);
    }
}

Output :
20 : is even and divisible by 5
16 :  is even but not divisible by 5
7 : is odd

So this is all about ternary Operators in Java. I hope you like the article. If you have any questions on this topic please raise them in the comments section.

Leave a Comment