Java Program to find the largest of three numbers using Ternary Operator

In this tutorial, we will learn how to write a Java Program to find the largest of three numbers using Ternary Operator.
We will read input from the console using Scanner class.

Java Program to find the largest of three numbers using Ternary Operator

package com.javaguides.java.tutorial;

import java.util.Scanner;

/**
 * Java Program to find largest of three numbers using Ternary Operator
 * 
 * @author https://www.sourcecodeexamples.net/
 *
 */
public class JavaProgram {
    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            int num1, num2, num3, temp;
            System.out.print("Enter first number:");
            num1 = (int) scanner.nextInt();

            System.out.print("Enter Second number:");
            num2 = (int) scanner.nextInt();

            System.out.print("Enter Third number:");
            num3 = (int) scanner.nextInt();

            temp = num1 > num2 ? num1 : num2;
            int result = num3 > temp ? num3 : temp;
            System.out.println("Largest Number is:" + result);
        }
    }
}
Output:
Enter first number:10
Enter Second number:2
Enter Third number:12
Largest Number is:12

Related Java Programs

Comments