Java ProgramsControl FlowFind Largest of Two Numbers

Find Largest of Two Numbers in Java

beginner·  Control Flow  ·  Conditional Statements

Problem

The larger of two numbers is whichever one exceeds the other — a single comparison settles it.

Given two integers, determine which one is the larger.

Input
8, 15
Output
Largest number: 15

Java Program

Java
public class LargestOfTwoNumbers { public static void main(String[] args) { int a = 8, b = 15; int largest; if (a > b) { largest = a; } else { largest = b; // also covers the tie case, where either value is a valid answer } System.out.println("Largest number: " + largest); } }

Output

Largest number: 15

Core Logic

Comparing the two numbers directly with a single greater-than check picks out the larger one in one step.

How It Works
  1. 1a > b checks whether the first number is strictly greater than the second.
  2. 2If true, a is assigned to largest.
  3. 3Otherwise, b is used instead — this covers both the case where b is larger and the case where the two are equal.
For 8 and 15, a > b is false, so largest takes b's value, 15.
💡

Key Point: Falling through to b in the else branch also correctly handles a tie — when both numbers are equal, either one is a valid 'largest', so returning b is fine.

Key Concepts

if/elsecomparison operator

Approach 2: Using Math.max()

Java
public class LargestOfTwoNumbersMathMax { public static void main(String[] args) { int a = 8, b = 15; // Math.max() picks the larger of the two directly int largest = Math.max(a, b); System.out.println("Largest number: " + largest); } }

Output

Largest number: 15

Core Logic

Java's own Math.max() already performs this exact comparison internally, so there's no need to write the if/else out by hand.

How It Works
  1. 1Math.max(a, b) compares the two arguments and returns whichever is larger.
  2. 2It handles a tie the same way the manual version does — returning either value when they're equal, since both are correct.
Math.max(8, 15) returns 15 directly.
💡

Key Point: Math.max() is overloaded for int, long, float, and double, so the exact same call works regardless of which numeric type is being compared.

Key Concepts

Math.max()built-in method

Related Programs