In this tutorial, you will learn how to write a Java program to find the largest of two numbers. We will understand the comparison logic first and then implement it using different practical approaches in Java programming.
Finding the larger value between two numbers is a basic programming exercise that helps beginners understand essential concepts, such as:
- Comparison operators
- If-else statements
- Taking user’s input using the Scanner class
- Ternary operator
We will cover the following approaches in this guide:
- Finding the largest of two numbers using a standard if-else statement.
- Accepting dynamic user input interactively using the Scanner class.
- Using the ternary operator for clean, concise comparisons.
- Properly handling edge cases—specifically when both numbers are equal.
How to Find the Largest of Two Numbers in Java?
To find the largest of two numbers, we compare the first number with the second number. Suppose the two numbers are num1 and num2.
The core comparison logic is straightforward:
- If
num1 > num2, thennum1is the larger number. - If
num2 > num1, thennum2is the larger number. - If neither number is greater, both numbers are equal.
Java provides relational operators—such as >, <, >=, and <=—for numerical comparisons. These comparisons always evaluate to a boolean result (true or false).
Java Program to Find the Largest of Two Numbers Using If-Else
The simplest approach to finding the larger value is by comparing two numbers using a standard if-else if-else statement. In this approach, we will directly assign two numbers to variables named num1 and num2.
Example 1: Using Hardcoded Numbers
// Java program to find the largest of two numbers using if-else
public class LargestOfTwoNumbers {
public static void main(String[] args) {
// Step 1: Declare and initialize two integer variables
int num1 = 45;
int num2 = 72;
// Step 2: Compare the two numbers using conditional statements
if (num1 > num2) {
// This block executes if num1 is greater than num2
System.out.println(num1 + " is the largest number.");
} else if (num2 > num1) {
// This block executes if num2 is greater than num1
System.out.println(num2 + " is the largest number.");
} else {
// This block acts as a fallback if neither is greater (i.e., they are equal)
System.out.println("Both numbers are equal.");
}
}
}Expected Output:
72 is the largest number.
In this program:
- We have declared two integer variables, num1 and num2, and initialized them with values.
- The first condition (num1 > num2) checks whether the first number is greater than the second. Since 45 > 72 evaluates to false, this block is skipped.
- The second condition (num2 > num1) checks the reverse (72 > 45). This evaluates to true, so it immediately prints that 72 is the largest number.
- If both comparisons are false, the numbers must be equal, so the else block is executed.
The equality case is important. For example, if both values are 50, neither 50 > 50 nor 50 > 50 is true. Therefore, the program reports that both numbers are equal.
Java Program to Find Largest of Two Numbers Using Scanner
In the previous example, we have assigned numbers directly to the variables. To make your programs dynamic and interactive, you can allow users to enter numbers from the keyboard at runtime.
To achieve this, we use the java.util.Scanner class, which allows Java to read input from the console.
Example 2: Accepting User Input Dynamically
// Java program to find the largest of two numbers using Scanner
// Import the Scanner class
import java.util.Scanner;
public class LargestUsingScanner {
public static void main(String[] args) {
// Step 1: Create a Scanner object to read input from standard input (keyboard)
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter the first number
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
// Step 3: Prompt the user to enter the second number
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Step 4: Compare the two numbers using if-else logic
if (num1 > num2) {
System.out.println("The largest number is: " + num1);
} else if (num2 > num1) {
System.out.println("The largest number is: " + num2);
} else {
System.out.println("Both numbers are equal (" + num1 + " = " + num2 + ").");
}
// Step 5: Close the scanner to prevent resource leaks
scanner.close();
}
}Expected Output:
Enter the first number: 85 Enter the second number: 42 The largest number is: 85
In this example program:
- The statement
import java.util.Scanner;imports the Scanner utility from Java’s standard library so your program can recognize it. - The statement
Scanner sc = new Scanner(System.in);creates a Scanner object that reads input from the standard input stream. - The
scanner.nextInt()method reads the next integer token entered by the user. - The
scanner.close()closes the scanner object to free up system resources and prevent memory leaks once input collection is complete.
Java Program to Find Largest of Two Numbers Using Ternary Operator
Java also provides the conditional operator (?:), commonly called the ternary operator. It is a clean, shorthand way to write simple conditional assignments without writing out a full if-else block.
The general syntax to declare ternary operator is:
condition ? valueIfTrue : valueIfFalseFor two numbers, we can write:
int largest = (num1 > num2) ? num1 : num2;
Example 3: Using the Ternary Operator
// Java program to find the largest of two numbers using the ternary operator.
public class LargestUsingTernary {
public static void main(String[] args) {
// Declare two numbers
int num1 = 50;
int num2 = 30;
// Use the ternary operator to find the largest number
int largest = (num1 > num2) ? num1 : num2;
// Print the result
System.out.println("The largest number is: " + largest);
}
}Expected Output:
The largest number is: 50
In this example program, the expression (num1 > num2) ? num1 : num2 works as follows:
- If num1 > num2 is true, the expression returns num1.
- If the condition is false, it returns num2.
- The returned value is stored in the largest variable.
Important Note on Equality:
If num1 and num2 are equal (e.g., both are 40), the condition num1 > num2 evaluates to false, so the ternary operator will safely return num2 (40).
While this is numerically correct since both are equal, either can be considered the maximum value. But it will not explicitly print a message saying “Both numbers are equal.” If you need to handle custom equality messages in a single line, you can use a nested ternary operator like this:
String result = (num1 == num2) ? "Both numbers are equal." :
(num1 > num2) ? num1 + " is the largest." :
num2 + " is the largest.";
System.out.println(result);Java Program to Find Largest of Two Numbers Using a Method
We can also place the comparison logic inside a user-defined method. This approach is useful when the operation needs to be performed multiple times.
Example 4: Using a User-Defined Method
// Java program to find the largest of two numbers using a separate method.
public class LargestOfTwoUsingMethod {
public static int findLargest(int num1, int num2) {
// If num1 is greater than num2, return num1; otherwise, return num2
return (num1 > num2) ? num1 : num2;
}
// Main method: entry point of the Java application
public static void main(String[] args) {
// Step 1: Declare and initialize the two numbers to compare
int num1 = 125;
int num2 = 98;
// Step 2: Call the helper method and store the returned result
int largest = findLargest(num1, num2);
// Step 3: Print the final result to the console
System.out.println("The largest number is: " + largest);
}
}Expected Output:
The largest number is: 125
In this program, findLargest() accepts two int values and returns the greater value. The method can also be called with different numbers:
findLargest(25, 50); findLargest(100, 75); findLargest(-10, -20);
This keeps the comparison logic reusable instead of repeating it throughout the program.
What Happens When Both Numbers Are Equal?
A common pitfall in beginner programming is forgetting to handle ties. Consider what happens when both input numbers are identical:
int num1 = 50;
int num2 = 50;When evaluating these values through standard conditional logic:
- The condition num1 > num2 evaluates to false.
- The condition num2 > num1 also evaluates to false.
Because both primary conditions fail, the program gracefully falls back to the else block.
Example Implementation:
public class EqualityCheckExample {
public static void main(String[] args) {
int num1 = 50;
int num2 = 50;
if (num1 > num2) {
System.out.println(num1 + " is the largest number.");
} else if (num2 > num1) {
System.out.println(num2 + " is the largest number.");
} else {
System.out.println("Both numbers are equal.");
}
}
}Expected Output:
Both numbers are equal.
Why This Matters: Explicitly handling equality ensures your program provides accurate, meaningful feedback rather than arbitrarily declaring one equal number as “larger” due to a faulty fallback condition.
Finding the Largest of Two Decimal Numbers in Java
So far, we have worked exclusively with whole numbers (int). However, real-world applications frequently handle fractional or decimal values—such as currency, scientific measurements, or percentages.
To compare decimal values in Java, you must use a floating-point data type like double (the standard choice for decimals) or float. The core comparison logic remains identical using relational operators (>, <, ==), but changing the data type ensures your program handles precision correctly.
Example 5: Comparing Two Decimal Numbers
// Java program to find the largest of two decimal numbers using double
public class LargestOfTwoDecimals {
public static void main(String[] args) {
// Step 1: Declare and initialize two double variables with decimal values
double num1 = 45.75;
double num2 = 52.33;
// Step 2: Compare the decimal values using standard if-else logic
if (num1 > num2) {
// Executes if num1 is greater
System.out.println(num1 + " is the largest number.");
} else if (num2 > num1) {
// Executes if num2 is greater
System.out.println(num2 + " is the largest number.");
} else {
// Executes if both decimal values are equal
System.out.println("Both decimal numbers are equal.");
}
}
}Expected Output:
52.33 is the largest number.
Key Takeaways:
- Why
double? In Java,doubleis the default data type for floating-point numbers. It offers double-precision 64-bit storage, making it much more accurate for mathematical comparisons thanfloat. - Seamless Logic: Notice that relational operators (
>) work seamlessly with decimal values just as they do with integers.







