VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-swap-two-variables/

⇱ Java Program to Swap two Variables - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Swap two Variables

Last Updated : 19 Jan, 2026

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
👁 Swapping of Two Numbers

Steps to Swap Two Numbers in Java

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

Methods for Swapping of Two Numbers in Java

1. Using Three Variables

Below is the implementation of the above method:


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:


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:


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.

Comment
Article Tags:
Article Tags: