Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find greatest among three numbers.

Java Code Example — Conditional Programs

ADVERTISEMENT

Java Program to find greatest among three numbers.

Objective

Write a Java program to find the largest among three numbers using logical AND (&&) operators.

Algorithm / Approach

  1. Read three numbers from the user and store them in x, y, and z.
  2. Check if x is greater than both y and z using x > y && x > z.
  3. If false, check if y is greater than z.
  4. If both conditions fail, then z must be the greatest.
  5. Print the greatest number.
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();
  System.out.print("Enter Z: ");
  int z = s.nextInt();
  if(x>y && x>z) {
   System.out.print("X is Greater");
  }
  else if(y>z) {
   System.out.print("Y is Greater");
  }
  else {
   System.out.print("Z is Greater");
  }
 }
}

Expected Output

Enter X: 15
Enter Y: 18
Enter Z: 12
Y is Greater

Explanation of the Program

  • The program uses an if-else if-else ladder.
  • The first condition x > y && x > z ensures that x is strictly greater than both other variables.
  • The second condition y > z only runs if the first condition fails (meaning x is not the greatest).
  • If y is also not greater than z, the else block automatically selects z as the maximum.

Complexity

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

Common Mistakes

  • Using the bitwise AND & instead of the logical AND &&.
  • Writing x > y > z which is mathematically valid but syntactically invalid in Java.
ADVERTISEMENT