Java find largest of three using ternary operator

In this post we are going to learn java find largest of three using ternary operator.

Java find largest of three using ternary operator

Java ternary operator is an alternative for if-else statement. Here’s the syntax,

variable output = expression ? value1 : value2;

Also read – largest number in java

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

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