Given two numbers x and y, we need to swap their values
Examples:
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) Asign temp to y : y = temp
Let us understand with an example.
x = 100, y = 200
After line 1: temp = x
temp = 100After line 2: x = y
x = 200After line 3 : y = temp
y = 100
// Java program to swap two variables public class GfG { public static void main(String[] args) { int x = 100, y = 200; System.out.println("Before Swap"); System.out.println("x = " + x); System.out.println("y = " + y); int temp = x; x = y; y = temp; System.out.println("After swap"); System.out.println("x = " + x); System.out.println("y = " + y); } } |
chevron_right
filter_none
Output:
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
Recommended Posts:
- Python Program to Swap Two Variables
- C Program to Swap two Numbers
- Python Program to swap two numbers without using third variable
- Java program to swap first and last characters of words in a sentence
- How to swap two numbers without using a temporary variable?
- TCS Coding Practice Question | Swap two Numbers
- C program to swap adjacent characters of a String
- Atomic Variables in Java with Examples
- Swap corner words and reverse middle characters
- Lexicographically largest string possible in one swap
- Swap characters in a String
- Lexicographically smallest array formed by at most one swap for every pair of adjacent indices
- Maximize distance between smallest and largest Array elements by a single swap
- Java Program for GCD of more than two (or array) numbers
- Java Program for Common Divisors of Two Numbers
- Java Program to Find the closest pair from two sorted arrays
- Java Program to find whether a no is power of two
- Java Program to Multiply two Matrices of any size
- Java Program to Add two Matrices
- Java Program for Program to calculate area of a Tetrahedron
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

