Ternary Operator In Java – Tutorial With Examples

This Tutorial Explains What is a Ternary Operator in Java, Syntax, and Benefits of Java Ternary Operator with the help of Various Code Examples:

In our earlier tutorial on Java Operator, we have seen various operators supported in Java including Conditional Operators.

In this tutorial, we will explore all about Ternary Operators which is one of the conditional operators.

=> Watch Out The Simple Java Training Series Here.

Ternary Operator In Java

What Is A Ternary Operator In Java?

We have seen the following conditional operators supported in Java in our tutorial on ‘Java Operators’.

OperatorDescription
&&Conditional-AND
||Conditional-OR
?:Ternary (shorthand for if-then-else statement)

Among the conditional operators listed above, the first two i.e. Conditional-AND and Conditional-OR are already covered in detail in our Logical operators tutorial.

Another significant and commonly used conditional operator supported is ternary operator  ‘?:’ which is also called as shorthand for an if-then-else statement.

Use Of Java Ternary Operator

Let’s see this Java Ternary Operator in detail.

Syntax:

Ternary operator has the following syntax:

resultValue = testConditionStatement ? value1 : value2;

In the above statement,

resultValueThis is the variable which gets value assigned
testConditionStatementThis is the test condition statement which gets evaluated which returns boolean value i.e.true or false
value1if testConditionStatement gets evaluated as ‘true’, then value1 gets assigned to resultValue
value2if testConditionStatement gets evaluated as ‘false’, then value2 gets assigned to resultValue

For Example, String resultString = (5>1) ? “PASS”: ”FAIL”;

In the above example, the ternary operator evaluates the test condition (5>1), if it returns true then assigns value1 i.e. “PASS” and assigns “FAIL” if it returns false. As (5>1) is true, resultString value gets assigned as “PASS”.

This operator is called as Ternary Operator because Ternary Operator uses 3 operands first is a boolean expression which evaluates to either true or false, second is the result when the boolean expression evaluates to true and the third is the result when the boolean expression evaluates to false.

Benefits Of Using Java Ternary Operator

As mentioned, the ternary operator is also called as shorthand for an if-then-else statement. It makes the code more readable.

Let’s see with the help of the following sample programs.

Ternary Operator Examples

Example 1: Use of Ternary operator as an alternative to if-else

Here is the sample program using simple if-else condition:

public class TernaryOperatorDemo1{
   public static void main(String[] args) {
    	int x = 5;
    	int y = 10;
    	
    	String resultValue = null;
    	if(x>=y) {
    		resultValue = "x is greater than or maybe equal to y";    		
    	}else {
    		resultValue = "x is less than y"; 
    	}
       System.out.println(resultValue); //o/p is x is less than y
  }
}

This program prints the following output :

x is less than y

Now, let us try to re-write the same code using a ternary operator as follows. In the above program, resultValue is assigned a value based on the evaluation of the expression (x>=y) in simple if and else condition.

public class TernaryOperatorDemo2{
  public static void main(String[] args) {
    	int x = 5;
    	int y = 10;
String resultValue=(x>=y)?"x is greater than or maybe equal to y":"x is less than y";
       System.out.println(resultValue); //o/p is x is less than y
  }
}

Note the following if-else code block in TernaryOperatorDemo1 class:

If(x>=y) {
    		resultValue = "x is greater than or maybe equal to y";    		
    	}else {
    		resultValue = "x is less than y"; 
    	}

This is been replaced with the following single line in TernaryOperatorDemo2 class:

String resultValue=(x>=y)?”x is greater than or maybe equal to y”:”x is less than y”;

This program prints the exact same output as TernaryOperatorDemo1 class:

x is less than y

This may not be appearing that signification change in a number of lines of code. But in a real scenario, the if-else condition is usually not that simple. Commonly, it is required to use the if-else-if statement. In such scenarios, the use of a ternary operator gives a significant difference in a number of lines of code.

Example 2: Use of Ternary operator as an alternative to if-else-if

i.e. Ternary operator with multiple conditions

Let’s see how a ternary operator can be used as an alternative to the if-else-if ladder.

Consider the following Java sample code:

public class TernaryOperatorDemo3{
  public static void main(String[] args) {
       int percentage=70;
       
       if(percentage>=60){  
           System.out.println("A grade");  
       }else if(percentage>=40){  
           System.out.println("B grade");  
       }else {  
           System.out.println("Not Eligible");  
       }
  }
}

In the above sample, the if-else-if condition is used to print an appropriate remark by comparing the percentage.

This program prints the following output :

A grade

Now, let us try to re-write the same code using a ternary operator as follows:

public class TernaryOperatorDemo4{
 public static void main(String[] args) {
   int percentage=70;  
        
   String resultValue = (percentage>=60)?"A grade":((percentage>=40)?"B grade":"Not    Eligible");
        System.out.println(resultValue); 
   }
}

Note the following if-else-if code block in TernaryOperatorDemo3 class:

if(percentage>=60){  
           System.out.println("A grade");  
       }else if(percentage>=40){  
           System.out.println("B grade");  
       }else {  
           System.out.println("Not Eligible");  
       }

This is been replaced with the following single line in TernaryOperatorDemo4 class:

String resultValue = (percentage>=60)?”A grade”:((percentage>=40)?”B grade”:”Not Eligible”);

This program prints the exact same output as TernaryOperatorDemo3 class:

This program prints the following output :

A grade

Example 3: Use of Ternary operator as an alternative to switch-case

Now, let us consider one more scenario with a switch-case statement.

In the following sample code, the switch-case statement is used to evaluate the value to be assigned to the String variable. i.e. color value is assigned based on colorCode integer value using the switch-case statement.

Given below is a sample Java code:

public class TernaryOperatorDemo5{
  public static void main(String[] args) {
        int colorCode = 101;
        String color = null;
        switch(colorCode) {
          case 100 :
     	   	color = "Yellow"; 
     	   	break;
          case 101 :
     	   	color = "Green";
     	   	break;
          case 102 : 
     	   	color = "Red";
     	   	break;
     	   default :
     		color = "Invalid";       
        }
       System.out.println("Color --->"+color);
  }
}

This program prints the following output :

Color —>Green

Now, let's see how a ternary operator can be helpful here to make the code simpler. So, let us re-write the same code using a ternary operator as follows:

public class TernaryOperatorDemo6{
 public static void main(String[] args) {
   int colorCode = 101;
   String color = null;   color=(colorCode==100)?"Yellow":((colorCode==101)?"Green":((colorCode==102)?"Red":"Invalid"));
    System.out.println("Color --->"+color);   }
}

Note the following switch-case code block in TernaryOperatorDemo5 class:

switch(colorCode) {
          case 100 :
     	   	color = "Yellow"; 
     	   	break;
          case 101 :
     	   	color = "Green";
     	   	break;
          case 102 : 
     	   	color = "Red";
     	   	break;
     	   default :
     		color = "Invalid";       
        }

This is been replaced with the following single line in TernaryOperatorDemo6 class:

color=(colorCode==100)?”Yellow”:((colorCode==101)?”Green”:((colorCode==102)?”Red”:”Invalid”));

This program prints the exact same output as TernaryOperatorDemo5:

This program prints the following output :

Color —>Green

FAQs

Q #1) Define a ternary operator in Java with an example.

Answer: Java Ternary operator is a conditional operator having the following syntax:

resultValue = testConditionStatement ? value1 : value2;

Here resultValue gets assigned as value1 or value2 based on testConditionStatement evaluation value as true or false respectively.

For Example , String result = (-1>0) ? “yes” : “no”;

result gets assigned value as “yes” if (-1>0) evaluates true and “no” if (-1>0) evaluates as false. In this case, the condition is true, hence, the value assigned to result is “yes”

Q #2) How do you write a ternary condition in Java?

Answer: As the name suggests, the Ternary operator uses 3 operands as follows:

resultValue = testConditionStatement ? value1 : value2;

testConditionStatement is a test condition which returns boolean value

value1 : value to be assigned when testConditionStatement returns true

value2 : value to be assigned when testConditionStatement returns false

For Example , String result = (-2>2) ? “yes” : “no”;

Q #3) What is the use and syntax of a Ternary operator?

Answer: Java Ternary operator follows the following syntax:

 resultValue = testConditionStatement ? value1 : value2;

The ternary operator is used as shorthand for if-then-else statement

Q #4) Is a Ternary operator faster than if?

Answer: Ternary is faster than if-else till there are no additional computations required to convert the logic to use ternary. It also enhances the readability of code.

Q #5) How do Ternary operators work?

Answer: The ternary operator takes three operands. The first argument is a test condition which returns a boolean value, the second is the value to be assigned when the boolean value returned is true, the third is the value to be assigned when the boolean value returned is false.

Conclusion

In this tutorial, we have covered the ternary operator ?: in detail.

We have seen syntax of the ternary operator, and why it is been called as shorthand for an if-then-else statement with the help of sample programs. We have also seen how it can be helpful to enhance the readability of the code using a switch-case statement.

=> Visit Here To Learn Java From Scratch.