**Swap two numbers without using third variable** is java program to swapping program in java without using third variable

In this tutorial, we are going to learn new program which is a simple program and most commonly used in exams or in interviews that is **Swap two numbers without using third variable**.

**What is swapping:** Swapping two number means replacing the numbers.

**How to swap two numbers without a third variable**

Swapping of two numbers in java

For swapping number first we have 2 numbers and without using third variable we swap numbers by doing a simple mathematical operation (sum and subtract )

1. Add first and second number and store addition in the first variable.

**a = a + b**

2. Subtract first and second number and store it in the second variable.

**b = a – b**

3. Subtract first and second number and store it in the first variable.

** a = a – b**

## Swapping program in java( without using third variable)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.*; public class Main { public static void main(String[] args) { int x,y, i=1; Scanner sc = new Scanner(System.in); System.out.print("Enter two Number : "); x = sc.nextInt(); y = sc.nextInt(); System.out.println("Before swaping:" + " x = " + x + ", y = " + y); x = x + y; y = x - y; x = x - y; System.out.println("After swaping:" + " x = " + x + ", y = " + y); } } |

**Output** :

**Explanation**:

**1. First we declare variable.**

x => for storing 1st number

y =>for storing the second number

2. Take input from user

x = sc.nextInt(); => x= 10

y = sc.nextInt(); => y= 20

**2. Now here goes the logic(let us take x= 10 and y=20)**

x = x+ y, Therefore, x=10+20 =30

y= x- y, Therefore y= 30 – 20 =10

x= x- y, Therefore x=30 – 10 = 20

**3. Now the values of x and y are 20 and 10**

**4. The values of x and y are printed.**

## Leave a Reply