Ternary Operator in Java


☞It is also known as conditional operator.

☞We can use it instead of if-else statement.

☞Syntax :

expression 1 ?  expression 2 : expression3

☞Expression 1 is condition, evaluated as true or false. When expression 1 is true, expression 2 is selected otherwise expression 3 is selected.

☞Lets see an example. We will write the following odd-even logic using ternary operator.

if(num%2 == 0)
    System.out.println("Even number");

else
    System.out.println("Odd number");

Example

import java.util.*;

public class TernaryExample {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter a number");
        int num=sc.nextInt();
        
        String result = (num%2 == 0) ? "Even number" : "Odd number";
        System.out.println(result);
    
    }
}

Output

Enter a number
45
Odd number

Note : While working with ternary operator, you will need a variable to store the result.