How to Accept Two Number and Print Largest Among Them in Java

The program allows users to input two numbers and then identifies and displays the largest of the two. 

It provides a simple illustration of how to compare two values and determine which one is the largest

How to Accept Values of Two Numbers and Print their Addition

In this program:
  1. Importing Required Libraries: The program starts by importing the necessary library java.util.Scanner to enable user input.
  2. Variable Declarations: It declares two integer variables, a and b.
    • a stores the first number entered by the user.
    • b stores the second number entered by the user.
  3. Creating a Scanner Object: A Scanner object named scanner is created to read input from the user.
  4. User Input: The program prompts the user to enter the first number with the message "Enter 1st number:" and the second number with "Enter 2nd number:". It reads these inputs as integers using scanner.nextInt() and stores them in the respective variables a and b.
  5. Closing the Scanner: After obtaining user input, the program closes the Scanner object using scanner.close() to release resources.
  6. Identifying the Largest Number: The program uses an if statement to compare the values of a and b. If a is greater than b, it prints "Largest value is: " followed by the value of a. Otherwise, if b is greater than or equal to a, it prints "Largest value is: " followed by the value of b.

import java.util.Scanner;

public class SwapValues {
    public static void main(String[] args) {
        int a, b, temp;
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter 1st number: ");
        a = scanner.nextInt();

        System.out.print("Enter 2nd number: ");
        b = scanner.nextInt();

        System.out.println("\nBefore Swapping...");
        System.out.println("A=" + a + ", B=" + b);

        temp = a;
        a = b;
        b = temp;

        System.out.println("\nAfter Swapping...");
        System.out.println("A=" + a + ", B=" + b);
    }
}
Join Now


Previous Year Questions Now to Boost Your Exam Performance

LOADS OF LOGIC