![]() |
VOOZH | about |
Given two integers m and n. The goal is to interchange the values of two variables using different approaches in Java.
Illustration:
Input: m=9, n=5
Output: m=5, n=9Input: m=15, n=5
Output: m=5, n=15
Here 'm' and 'n' are integer value
Before swapping: m = 9, n = 5 After swapping: m = 5, n = 9
Note: This swap only affects local copies in memory. If you pass m and n to a method, the original variables remain unchanged due to Java's pass-by-value.
Algorithms: The arithmetic swapping method works in the following steps
Before swapping: m = 9, n = 5 After swapping: m = 5, n = 9
Note: This method avoids extra variables but can cause overflow with very large numbers.
Illustration:
a = 5 -> 0101 (binary)
b = 7 -> 0111 (binary)XOR Operation: a ^ b
0101
^ 0111
------
0010 -> 2 (decimal)
Using XOR twice can swap two numbers efficiently without extra memory:
a = a ^ b;
b = a ^ b;
a = a ^ b;
Before swapping: m = 9, n = 5 After swapping: m = 5, n = 9
The previous methods only swaps local copies. To swap numbers in a method and reflect changes outside, we use an array.
Before swapping: m = 9, n = 5 After swapping using array: m = 5, n = 9