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
- Read three numbers from the user and store them in
x,y, andz. - Check if
xis greater than bothyandzusingx > y && x > z. - If false, check if
yis greater thanz. - If both conditions fail, then
zmust be the greatest. - 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-elseladder. - The first condition
x > y && x > zensures thatxis strictly greater than both other variables. - The second condition
y > zonly runs if the first condition fails (meaningxis not the greatest). - If
yis also not greater thanz, theelseblock automatically selectszas 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 > zwhich is mathematically valid but syntactically invalid in Java.