Java Program to Swap two Variables
Given two numbers x and y, we need to swap their values
Input : x = 10, y = 20; Output : x = 20, y = 10 Input : x = 200, y = 100 Output : x = 100, y = 200
Below are the simple steps we follow:
1) Assign x to a temp variable : temp = x
2) Assign y to x : x = y
3) Assign temp to y : y = temp
Let us understand with an example.
x = 100, y = 200
After line 1: temp = x
temp = 100
After line 2: x = y
x = 200
After line 3 : y = temp
y = 100
Before Swap x = 100 y = 200 After swap x = 200 y = 100
- How to swap two numbers without using a temporary variable?
- How to swap or exchange objects in Java?
- Swap two variables in one line in C/C++, Python, PHP and Java