Swap Variables in Java

Learn different techniques to exchange variable values

🔄 Swapping Variables in Java

Swapping means exchanging the values of two variables. Java offers multiple approaches including temporary variables, arithmetic operations, and XOR bitwise operations for swapping.


// Before swap: a=10, b=20
int temp = a;
a = b;
b = temp;
// After swap: a=20, b=10
                                    

Different Swapping Methods

📦

Using Temp Variable

Most common and safe method

int temp = a;
a = b;
b = temp;

Using Addition

Arithmetic approach without temp

a = a + b;
b = a - b;
a = a - b;
✖️

Using Multiplication

Alternative arithmetic method

a = a * b;
b = a / b;
a = a / b;

Using XOR

Bitwise operation method

a = a ^ b;
b = a ^ b;
a = a ^ b;

🔹 Complete Example Program

Here's a complete Java program demonstrating variable swapping:

import java.util.Scanner;

public class SwapVariables {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter first number: ");
        int a = scanner.nextInt();
        
        System.out.print("Enter second number: ");
        int b = scanner.nextInt();
        
        System.out.println("Before swapping: a = " + a + ", b = " + b);
        
        // Swapping using temporary variable
        int temp = a;
        a = b;
        b = temp;
        
        System.out.println("After swapping: a = " + a + ", b = " + b);
        
        scanner.close();
    }
}

Sample Output:

Enter first number: 15

Enter second number: 25

Before swapping: a = 15, b = 25

After swapping: a = 25, b = 15

🔹 Method Comparison

Temporary Variable Method:

  • Pros: Safe, works with all data types, easy to understand
  • Cons: Uses extra memory for temp variable

Arithmetic Methods:

  • Pros: No extra variable needed
  • Cons: Risk of overflow, only works with numbers

XOR Method:

  • Pros: No overflow risk, no extra variable
  • Cons: Only works with integers, harder to understand

🧠 Test Your Knowledge

Which swapping method is safest for all data types?