Java program to find largest in three numbers using ternary operator

Let’s learn java program to find largest in three numbers using ternary operator.

Java program to find largest in three numbers using ternary operator

write a program in java to find maximum of three numbers using conditional operator is one of the common interview question.

java program to find largest in three numbers using ternary operator

Java ternary operator is an alternative for if-else statement. In the below java program user enters three numbers.

Then ternary operator is used to find largest number. Here’s the syntax of ternary operator in java,

output = (expression) ? value1 (if true) : value2 (if false)

If expression is true then ternary operator returns first value else second value is returned. Now let’s see program to find largest of three numbers using ternary operator.

import java.util.Scanner;
public class LargestInThree 
{
   public static void main(String[] args) 
   {
      int number1, number2, number3, largest;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter first number: ");
      number1 = sc.nextInt();
      System.out.println("Please enter second number: ");
      number2 = sc.nextInt();
      System.out.println("Please enter third number: ");
      number3 = sc.nextInt();
      largest = number3 > (number1 > number2 ? number1 : number2) ? number3 : ((number1 > number2) ? number1 : number2);
      System.out.println("Largest in three numbers using ternary operator: " + largest);
      sc.close();
   }
}


Output:

Please enter first number: 665
Please enter second number: 268
Please enter third number: 263
Largest in three numbers using ternary operator: 665