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

Java program to find largest in three numbers using ternary operator

Find biggest of three numbers using conditional operator/ternary operator in java is one of the common interview question.

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.

Also read – operators in java

Here’s the syntax,

variable 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 java program,

import java.util.Scanner;

public class LargestOfThree
{
public static void main(String[] args)
{
int number1, number2, number3, output, temp;
Scanner sc = new Scanner(System.in);
System.out.println("First number : ");
number1 = sc.nextInt();
System.out.println("Second number : ");
number2 = sc.nextInt();
System.out.println("Third number : ");
number3 = sc.nextInt();
temp = number1 > number2 ? number1 : number2;
output = number3 > temp ? number3 : temp;
System.out.println("Largest Number : " + output);
sc.close();
}
}

Output:

First number : 33
Second number : 56
Third number : 59
Largest Number : 59