This is a Java program that illustrates situations where two numbers will be swapped.
Explaining Different Swapping Methods:
Using a Temporary Variable- Store a number in a temporary variable.
- Swap the values by assigning them correctly as follows exactly the same workmethod
- Adding and subtracting to swap in arithmetic
- Risk: Possible overflow for large number if that number you see is right due to introduction extra space (for temporary variable)
- XOR is an efficient solution to swapping numbers.
- Applies to int types
- use of arithmetic.
- Single line swap, no extra variable required.
Swap two numbers in Java example program
- import java.util.Scanner;
- public class SwapNumbers {
- // Swap two numbers in java using a temporary variable
- public static void swapWithTemp(int a, int b) {
- System.out.println("Before Swap: a = " + a + ", b = " + b);
- int temp = a;
- a = b;
- b = temp;
- System.out.println("After Swap: a = " + a + ", b = " + b);
- }
- // Swap two numbers without using a temporary variable (using arithmetic operations)
- public static void swapWithoutTemp(int a, int b) {
- System.out.println("Before Swap: a = " + a + ", b = " + b);
- a = a + b;
- b = a - b;
- a = a - b;
- System.out.println("After Swap: a = " + a + ", b = " + b);
- }
- // Swap two numbers using bitwise XOR operator
- public static void swapWithXOR(int a, int b) {
- System.out.println("Before Swap: a = " + a + ", b = " + b);
- a = a ^ b;
- b = a ^ b;
- a = a ^ b;
- System.out.println("After Swap: a = " + a + ", b = " + b);
- }
- // Swap two numbers in java using a single statement (tuple swap)
- public static void swapSingleStatement(int a, int b) {
- System.out.println("Before Swap: a = " + a + ", b = " + b);
- b = (a + b) - (a = b);
- System.out.println("After Swap: a = " + a + ", b = " + b);
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter first number: ");
- int num1 = scanner.nextInt();
- System.out.print("Enter second number: ");
- int num2 = scanner.nextInt();
- System.out.println("\nSwapping using a temporary variable:");
- swapWithTemp(num1, num2);
- System.out.println("\nSwapping without using a temporary variable:");
- swapWithoutTemp(num1, num2);
- System.out.println("\nSwapping using XOR operator:");
- swapWithXOR(num1, num2);
- System.out.println("\nSwapping using a single statement:");
- swapSingleStatement(num1, num2);
- scanner.close();
- }
- }
No comments