Largest of Two Numbers

Find the largest of two numbers using if-else.

BeginnerTopic: Module 1: Basic Java Programs
Back

Java Largest of Two Numbers Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double a = sc.nextDouble();

        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        if (a > b) {
            System.out.println("Largest = " + a);
        } else if (b > a) {
            System.out.println("Largest = " + b);
        } else {
            System.out.println("Both numbers are equal");
        }

        sc.close();
    }
}
Output
Enter first number: 5
Enter second number: 9
Largest = 9.0

Understanding Largest of Two Numbers

We compare the two numbers using > and handle the equal case separately.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents