Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find greatest among two numbers using ternary number.

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to find greatest among two numbers using ternary number.

Objective

Write a Java program to find the greatest of two numbers using the ternary operator.

Algorithm / Approach

  1. Prompt the user to enter two numbers.
  2. Use the ternary operator (x > y) ? x : y to compare them.
  3. Store the result in a variable and print it.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Num1: ");
  int x = s.nextInt();
  System.out.print("Enter Num2: ");
  int y = s.nextInt();
  int r = (x>y)?x:y;
  System.out.print("Largest = "+r);
 }
}

Expected Output

Enter Num1: 10
Enter Num2: 30
Largest = 30

Explanation of the Program

  • Two numbers, x and y, are input by the user.
  • The ternary operator (x > y) ? x : y is used to check the condition.
  • If x is greater than y, it evaluates to x; otherwise, it evaluates to y.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Using if-else statements when specifically asked to use a ternary operator.
  • Syntax errors with the ? and : operators.
ADVERTISEMENT