The Java program to swap two numbers, first using three variables and then using two variables:
1. Using Three Variables
java
Copy code
import java.util.Scanner;
public class SwapUsingThreeVariables {
public static void main(String[] args) {
// Create a scanner object for input
Scanner scanner = new Scanner(System.in);
// Input two numbers
System.out.print("Enter first number: ");
int a = scanner.nextInt();
System.out.print("Enter second number: ");
int b = scanner.nextInt();
// Using third variable to swap
int temp = a; // Store the value of 'a' in 'temp'
a = b; // Assign value of 'b' to 'a'
b = temp; // Assign value of 'temp' (original 'a') to 'b'
// Output the swapped values
System.out.println("After swapping:");
System.out.println("First number: " + a);
System.out.println("Second number: " + b);
// Close the scanner
scanner.close();
}
Explanation:
• A temporary variable temp is used to hold the value of a while the value of b is assigned to a.
Then, the value in temp (which is the original value of a) is assigned to b.
Expected Output:
yaml
Copy code
Enter first number: 5
Enter second number: 10
After swapping:
First number: 10
Second number: 5
2. Using Two Variables
java
Copy code
import java.util.Scanner;
public class SwapUsingTwoVariables {
public static void main(String[] args) {
// Create a scanner object for input
Scanner scanner = new Scanner(System.in);
// Input two numbers
System.out.print("Enter first number: ");
int a = scanner.nextInt();
System.out.print("Enter second number: ");
int b = scanner.nextInt();
// Using arithmetic operations to swap without a third variable
a = a + b; // Step 1: a becomes the sum of a and b
b = a - b; // Step 2: b becomes the original value of a
a = a - b; // Step 3: a becomes the original value of b
// Output the swapped values
System.out.println("After swapping:");
System.out.println("First number: " + a);
System.out.println("Second number: " + b);
// Close the scanner
scanner.close();
Explanation:
• Step 1: Add the values of a and b and store the result in a. Now a holds the sum of both
numbers.
• Step 2: Subtract b from the new value of a to get the original value of a and assign it to b.
• Step 3: Subtract the new value of b (which is the original a) from a to get the original value of b
and assign it to a.
Expected Output:
yaml
Copy code
Enter first number: 5
Enter second number: 10
After swapping:
First number: 10
Second number: 5