In this Java program, we will learn how to find the largest number among three numbers entered by the user using the if-else statement.
Java Program
import java.util.Scanner;
public class LargestAmongThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.print("Enter third number: ");
int num3 = sc.nextInt();
int largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
System.out.println("Largest number = " + largest);
sc.close();
}
}
Output
Enter first number: 25
Enter second number: 40
Enter third number: 15
Largest number = 40
Explanation
The program accepts three numbers from the user using the Scanner class.
The if-else if-else statement compares the three numbers:
if (num1 >= num2 && num1 >= num3)
If num1 is greater than or equal to both other numbers, it is the largest.
Similarly, the program checks num2. If neither num1 nor num2 is the largest, then num3 is considered the largest.
The && operator is used to check multiple conditions at the same time.
Key Points
Scanneris used to accept input from the user.if-elseis used to compare three numbers.- The
&&logical operator combines multiple conditions. - The program works with Java 8 and later versions.
Conclusion
This Java program demonstrates how to compare three numbers and find the largest number using conditional statements.
Using Java 8
For Java 8, you can write it using the Math.max() method. This is shorter and cleaner than multiple if-else statements.
Java 8: Program to Find the Largest Among Three Numbers
import java.util.Scanner;
public class LargestAmongThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.print("Enter third number: ");
int num3 = sc.nextInt();
int largest = Math.max(num1, Math.max(num2, num3));
System.out.println("Largest number = " + largest);
sc.close();
}
}
Output
Enter first number: 25
Enter second number: 40
Enter third number: 15
Largest number = 40
Explanation
Java provides the Math.max() method to find the larger of two numbers.
Math.max(num2, num3)
First, it finds the larger value between num2 and num3. Then that result is compared with num1:
Math.max(num1, Math.max(num2, num3))
This gives the largest number among all three numbers.