Java Program to Find the Largest of Three Numbers
Finding the largest among three numbers is a common beginner-level problem in Java. It helps learners understand conditional statements and logical comparisons.
In this tutorial, we will create a simple Java program that takes three numbers as input and determines the largest among them.
By the end of this guide, you will understand how comparison operators and if-else logic work in Java.
Concept Overview
To find the largest of three numbers, we compare them using relational operators like > (greater than).
We use if-else if-else statements to determine which number is the largest.
The logic involves comparing the first number with the other two, then checking the remaining possibilities.
Program
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.print("Enter third number: ");
int c = sc.nextInt();
if (a >= b && a >= c) {
System.out.println(a + " is the largest");
} else if (b >= a && b >= c) {
System.out.println(b + " is the largest");
} else {
System.out.println(c + " is the largest");
}
}
}
Output
Enter first number: 10
Enter second number: 25
Enter third number: 15
25 is the largest
Detailed Explanation
The program begins by importing the Scanner class for user input.
Three integer variables a, b, and c are used to store the input values.
The program uses if-else if-else conditions to compare the numbers.
First, it checks whether a is greater than or equal to both b and c.
If not, it checks whether b is greater than or equal to both a and c.
If neither condition is true, then c is the largest number.
Example Walkthrough
Let us consider an example where the user enters 10, 25, and 15.
The program compares all values and determines that 25 is the largest.
The output is displayed as '25 is the largest'.
Applications
This logic is used in ranking systems, scoring systems, and decision-making algorithms.
It is also useful in data analysis and comparative computations.
Advantages of This Approach
This program is simple and helps beginners understand conditional logic clearly.
It demonstrates how multiple conditions can be combined using logical operators.
Limitations
The program assumes valid integer input and does not handle invalid input.
Improvements You Can Make
You can extend this program to find the largest among N numbers using loops.
You can also add input validation for better robustness.
You can modularize the logic using functions for better reusability.
This Java program helps build strong foundations in decision-making and comparison logic, which are essential in programming.
Codecrown