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
In this program:
- Importing Required Libraries: The program starts by importing the necessary library
java.util.Scannerto enable user input. - Variable Declarations: It declares two integer variables,
aandb. astores the first number entered by the user.bstores the second number entered by the user.- Creating a Scanner Object: A
Scannerobject namedscanneris created to read input from the user. - 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 variablesaandb. - Closing the Scanner: After obtaining user input, the program closes the
Scannerobject usingscanner.close()to release resources. - Identifying the Largest Number: The program uses an
ifstatement to compare the values ofaandb. Ifais greater thanb, it prints "Largest value is: " followed by the value ofa. Otherwise, ifbis greater than or equal toa, it prints "Largest value is: " followed by the value ofb.
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);
}
}

Follow Us