Java Program to find the greatest among two numbers.
Objective
Write a Java program to find the largest of two given numbers using an if-else statement.
Algorithm / Approach
- Prompt the user to enter two numbers.
- Store them in variables
xandy. - Use an
ifcondition to check ifx > y. - If true, print that
Xis greater. - Otherwise, print that
Yis greater.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter X: ");
int x = s.nextInt();
System.out.print("Enter Y: ");
int y = s.nextInt();
if(x>y) {
System.out.print("X is Greater");
}
else {
System.out.print("Y is Greater");
}
}
}
Expected Output
Enter X: 15 Enter Y: 20 Y is Greater
Explanation of the Program
- The program reads two integers from the standard input using
Scanner. - The
if-elseblock compares the two numbers. - When
x > yevaluates to true, the block inside theifstatement executes. - If it evaluates to false, the block inside the
elsestatement executes instead.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Forgetting the curly braces
{}around the if-else blocks (although optional for single lines, they are highly recommended for clarity). - Not handling the scenario where both numbers are exactly equal.