Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Conditional Constructs in Java

Chapter 8

Conditional Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Largest of Three Numbers Using Ternary Operator


21. Using the ternary operator, create a program to find the largest of three numbers.

import java.util.Scanner;

 

public class LargestOfThree {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        // Input three numbers

        System.out.print("Enter first number: ");

        int a = sc.nextInt();

 

        System.out.print("Enter second number: ");

        int b = sc.nextInt();

 

        System.out.print("Enter third number: ");

        int c = sc.nextInt();

 

        // Finding largest using ternary operator

        int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

 

        // Output

        System.out.println("Largest number is: " + largest);

 

        sc.close();

    }

}

Output

Sample Input 
Enter first number: 25
Enter second number: 40
Enter third number: 15

Sample Output 
Largest number is: 40

Explanation

  • The ternary operator checks conditions in a compact form:

                 (condition) ? value_if_true : value_if_false

  • First comparison checks between a and b.
  • The larger of those is then compared with c.
  • The final result is stored in largest.