Middle
How to swap the values of two variables without using a third variable?
sobes.tech AI
Answer from AI
In Java, you can swap the values of two variables without using a third variable in several ways.
- Using arithmetic operations (for numeric types):
int a = 5;
int b = 10;
a = a + b; // a = 15
b = a - b; // b = 5
a = a - b; // a = 10
- Using bitwise XOR (for integer types):
int a = 5;
int b = 10;
a = a ^ b; // a = 15 (0101 ^ 1010 = 1111)
b = a ^ b; // b = 5 (1111 ^ 1010 = 0101)
a = a ^ b; // a = 10 (1111 ^ 0101 = 1010)
Both methods swap variable values without additional memory. However, be cautious of overflow with arithmetic operations and use them only with appropriate types.