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
- Prompt the user to enter two numbers.
- Use the ternary operator
(x > y) ? x : yto compare them. - 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,
xandy, are input by the user. - The ternary operator
(x > y) ? x : yis used to check the condition. - If
xis greater thany, it evaluates tox; otherwise, it evaluates toy.
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.