The Java Program To Swap Two Numbers
The Java Program To Swap Two Numbers
java
Copy code
import java.util.Scanner;
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("After swapping:");
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
After swapping:
First number: 10
Second number: 5
java
Copy code
import java.util.Scanner;
int a = scanner.nextInt();
int b = scanner.nextInt();
// Using arithmetic operations to swap without a third variable
System.out.println("After swapping:");
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
After swapping:
First number: 10
Second number: 5