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.Scanner
to enable user input. - Variable Declarations: It declares two integer variables,
a
andb
. a
stores the first number entered by the user.b
stores the second number entered by the user.- Creating a Scanner Object: A
Scanner
object namedscanner
is 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 variablesa
andb
. - Closing the Scanner: After obtaining user input, the program closes the
Scanner
object usingscanner.close()
to release resources. - Identifying the Largest Number: The program uses an
if
statement to compare the values ofa
andb
. Ifa
is greater thanb
, it prints "Largest value is: " followed by the value ofa
. Otherwise, ifb
is 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