Largest of Two Numbers in Java
Find the largest of two numbers using if-else.
BeginnerModule 1: Basic Java ProgramsExample 6 of 20
largest-of-two-numbers.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter first number: ");8 double a = sc.nextDouble();910 System.out.print("Enter second number: ");11 double b = sc.nextDouble();1213 if (a > b) {14 System.out.println("Largest = " + a);15 } else if (b > a) {16 System.out.println("Largest = " + b);17 } else {18 System.out.println("Both numbers are equal");19 }2021 sc.close();22 }23}
Output
Enter first number: 5 Enter second number: 9 Largest = 9.0
What's going on
We compare the two numbers using > and handle the equal case separately.