- Using Arithmetic Operations
You can swap two numbers a and b without using a third variable by using basic arithmetic operations like addition and subtraction. This method is applicable to numeric data types (e.g., int, double).
public class SwapWithoutThirdVariable {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
// Swapping using arithmetic operations
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Output:
Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10
- Using Bitwise XOR Operation:
You can also swap two numbers a and b using the bitwise XOR (^) operation. This method is applicable to integer data types.
public class SwapWithoutThirdVariable {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
// Swapping using bitwise XOR operation
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After swapping:");
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Output:
Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10
In both methods, the two numbers are swapped without using an additional third variable. These techniques rely on the mathematical properties of arithmetic or bitwise XOR operations to perform the swap. These methods are efficient and commonly used when you want to swap two variables without using extra memory.
No comments:
Post a Comment