Java program to find largest in three numbers using ternary operator

In this post we are going to 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

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 – largest number in java

Here’s the syntax,

variable output = expression ? value1 : value2;

If expression is true then ternary operator returns first value else second value. 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

Related Posts