🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

WAP to find the largest of two numbers in Java  


Logical Steps:
  • To find the largest of two numbers, follow these steps:
    1. Take two numbers.
    2. Compare the two numbers using conditional statements.
    3. Use an if-else statement to determine which number is larger.
    4. Print the larger number as the result.
Program:
  • Below is the simple program:
    public class LargestOfTwoNumbers
    {
        public static void main(String[] args)
        {
            int no1=10, no2=20;
    
            // Finding and displaying the largest number
            if (no1 > no2)
            {
                System.out.println("The largest number is : " + no1);
            }
            else if (no2 > no1)
            {
                System.out.println("The largest number is : " + no2);
            }
            else
            {
                System.out.println("Both numbers are equal.");
            }
        }
    }
    Output:
    The largest number is : 20
  • Below is the program by taking user input:
    import java.util.Scanner;
    
    public class LargestOfTwoNumbers
    {
        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter number 1: ");
            int no1 = scanner.nextInt();
    
            System.out.print("Enter number 2: ");
            int no2 = scanner.nextInt();
    
            // Finding and displaying the largest number
            if (no1 > no2)
            {
                System.out.println("\nThe largest number is : " + no1);
            }
            else if (no2 > no1)
            {
                System.out.println("\nThe largest number is : " + no2);
            }
            else
            {
                System.out.println("\nBoth numbers are equal.");
            }
    
            scanner.close();
        }
    }
    Output:
    Enter number 1: 100
    Enter number 2: 200
    
    The largest number is : 200
Program Explanation:
  • Import Scanner Class:
    • The Scanner class is imported to take user input.
  • Declare Variables:
    • Two integer variables (no1 and no2) are declared to store the user’s input.
  • Take Input:
    • Use scanner.nextInt() to read integer values from the user.
  • Comparison Logic:
    • The if condition checks if no1 is greater than no2 and prints it as the largest.
    • If the else if condition is true, no2 is the largest.
    • If both numbers are equal, the program prints a message indicating that.
  • Close Scanner:
    • The scanner.close() method is used to close the input stream and release resources.