C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Largest of Two Numbers Using Ternary Operator

import java.util.Scanner;

 

public class LargestUsingTernary {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

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

        int a = sc.nextInt();

 

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

        int b = sc.nextInt();

 

        // Ternary operator

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

 

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

 

        sc.close();

    }

}

Output

 
OUTPUT 1:

INPUT :
Enter first number: 25
Enter second number: 15

OUTPUT : 
Largest number is: 25

OUTPUT 2:

INPUT :
Enter first number: 10
Enter second number: 30

OUTPUT : 
Largest number is: 30
 

Explanation

1. What is the Ternary Operator?

The ternary operator is a short form of if-else.

Syntax:

condition ? value_if_true : value_if_false;

2. Logic Used

(a > b) ? a : b

  • If a > b → result is a
  • Else → result is b

3. Program Flow

  1. Read two numbers from the user
  2. Compare using ternary operator
  3. Store the larger value
  4. Display the result

Key Advantages

  • Compact and readable
  • Faster comparison
  • Often used in interviews