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.
Examples of Swapping
Input : x = 10, y = 20;
Output : x = 20, y = 10
Input : x = 213, y = 109
Output : x = 109, y = 213

Steps to Swap Two Numbers in Java
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
Methods for Swapping of Two Numbers in Java
1. Using Three Variables
Below is the implementation of the above method:
public class GfG {
// main function
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);
// Swapping using three
// Variables
int temp = x;
x = y;
y = temp;
System.out.println("After swap");
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
Output
Before Swap x = 100 y = 200 After swap x = 200 y = 100
2. Using Two Variables
Below is the implementation of the above method:
import java.io.*;
// Driver Class
public class SwapVariables {
// main function
public static void main(String[] args)
{
int a = 5;
int b = 10;
// print statement
System.out.println("Before swapping, a = " + a
+ " and b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping, a = " + a
+ " and b = " + b);
}
}
Output
Before swapping, a = 5 and b = 10 After swapping, a = 10 and b = 5
3. Using Two Variables (Single Statement)
Below is the implementation of the above method:
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
Integer a = 10;
Integer b = 20;
System.out.println("Before swapping, a = " + a
+ " and b = " + b);
// Swapping a and b using
// below statement
b = a + b - (a = b);
System.out.println("Before swapping, a = " + a
+ " and b = " + b);
}
}
Output
Before swapping, a = 10 and b = 20 Before swapping, a = 20 and b = 10
4.Using XOR
We can swap the numbers using XOR operator as shown below.
import java.io.*;
class GFG {
public static void main (String[] args) {
int a = 10;
int b = 20;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Swapping a and b using XOR
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After swapping, a = " + a + " and b = " + b);
}
}
Output
Before swapping, a = 10 and b = 20 After swapping, a = 20 and b = 10