![]() |
VOOZH | about |
Given two numbers x and y, we need to swap their values. In this article, we will learn the Swapping of two numbers in Java.
Input : x = 10, y = 20;👁 Swapping of Two Numbers
Output : x = 20, y = 10
Input : x = 213, y = 109
Output : x = 109, y = 213
Below are the simple steps we follow:
- Assign x to a temp variable: temp = x
- Assign y to x: x = y
- Assign temp to y: y = temp
Below is the implementation of the above method:
Before Swap x = 100 y = 200 After swap x = 200 y = 100
Below is the implementation of the above method:
Before swapping, a = 5 and b = 10 After swapping, a = 10 and b = 5
Below is the implementation of the above method:
Before swapping, a = 10 and b = 20 Before swapping, a = 20 and b = 10
We can swap the numbers using XOR operator as shown below.
Before swapping, a = 10 and b = 20 After swapping, a = 20 and b = 10