Java Ternary operator with example

Java Ternary operator is a conditional operator and an only operator that accepts 3 operands. We can replace the if-else-then statement by one-liner using the ternary operator.

variable = Expression1 ? Expression2 : Expression3

The following expression evaluates to:

if(Expression1){
  variable = Expression2 ;
}
else{
  variable = Expression3 ;
}

For eg:

say n1 = 5 ;

n2 = 10 ;

ans = (n1>n2) ? n1+5 : n2-5

In this example, ans=5 because:

if(n1>n2){

ans = n1+5 ;

}else{

ans = n2 – 5 ;

}

The code given below explains the multiple if-else statement using ternary operator. Please, observe answer to both code is same.

import java.io.*;

class CodeSpeedy {
  public static void main (String[] args) {
    int n1 = 5 ;
    int n2 = 7 ;
    int n3 = 9;
    
    
    
    int result = (n1>n2) ? 1 : (n1>n3) ? 2 : (n1<n2 && n1<n3) ? 3 : 0;
    System.out.println("Result using ternary operator:" + result);
    
    if(n1>n2){
        result = 1 ;
    }else if(n1>n3){
        result = 2 ;
    }else if(n1<n2 && n1<n3){
        result = 3;
    }else{
        result = 0 ;
    }
    
    System.out.println("Result using if-else-then statement:" + result);
    
  }
}

The output of the above code is:

Result using ternary operator:3
Result using if-else-then statement:3

It is advised, in case of multiple if-else, use if-else syntax instead of a ternary operator as it increases readability.

Also read: Password Validation Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *