Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find the greatest among two numbers.

Java Code Example — Conditional Programs

ADVERTISEMENT

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

  1. Prompt the user to enter two numbers.
  2. Store them in variables x and y.
  3. Use an if condition to check if x > y.
  4. If true, print that X is greater.
  5. Otherwise, print that Y is 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-else block compares the two numbers.
  • When x > y evaluates to true, the block inside the if statement executes.
  • If it evaluates to false, the block inside the else statement 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.
ADVERTISEMENT