Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find greatest among three numbers using nested if else.

Java Code Example — Conditional Programs

ADVERTISEMENT

Java Program to find greatest among three numbers using nested if else.

Objective

Write a Java program to find the largest among three numbers using nested if-else statements.

Algorithm / Approach

  1. Read three numbers into variables x, y, and z.
  2. First, use an outer if to check if x > y.
  3. If true, use an inner if to check if x > z. If yes, X is greatest; otherwise Z is greatest.
  4. If the outer condition is false, check if y > z. If yes, Y is greatest; otherwise Z is greatest.
  5. Print the result.
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) {
   if(x>z) {
    System.out.print("X is Greater");
   }
   else {
    System.out.print("Z is Greater");
   }
  }
  else {
   if(y>z) {
    System.out.print("Y is Greater");
   }
   else {
    System.out.print("Z is Greater");
   }
  }
 }
}

Expected Output

Enter X: 10
Enter Y: 18
Enter Z: 14
Y is Greater

Explanation of the Program

  • This program avoids the logical AND operator by placing if statements inside other if statements.
  • The outer block narrows down the maximum candidate to either x or y.
  • The inner blocks then compare that winning candidate against z to find the absolute maximum.
  • This approach demonstrates how control flow can branch hierarchically.

Complexity

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

Common Mistakes

  • Poor indentation, which makes it extremely hard to see which else belongs to which if.
ADVERTISEMENT