# Frequently Asked Java Program 05: Swap two integer variables without using third variable

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a Java program to swap values of two integer variables without using third variable.

### Problem Statement:

Write a java program to swap values of two integer variables without using third variable.

### Solution:

It is very commonly asked interview program. In Fact it is less program more mathematics.

1. Let’s assume there are two variables with some values:

a =10

b=20

2. Now add a and b and store in a:

a = a+b => 10+20 => 30

b= 20

3. Now subtract b from a and store in b:

a= 30

b = a – b => 30-20 => 10

4. Now subtract b from a and store in a:

a= a – b = > 30-10 = > 20

b= 10

5. Notice here that both variables a and b have interchange their values.

Let’s convert above logic into a Java Program.

##### Java Program:
```import java.util.Scanner;

public class SwappingTwoNumbers {

public static void main(String[] args) {

// taking input from user
Scanner in = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int x = in.nextInt();
System.out.println("Enter the 2nd number: ");
int y = in.nextInt();

// printing values before swap
System.out.println("Before Swap: ");
System.out.println("Value of x: "+x);
System.out.println("Value of y: "+y);

// swapping without using third variable
x = x+y;
y = x-y;
x = x-y;

// printing values after swap
System.out.println("After Swap: ");
System.out.println("Value of x: "+x);
System.out.println("Value of y: "+y);
}
}
```

Output:

```[java]
Enter the 1st number:
21
Enter the 2nd number:
33
Before Swap:
Value of x: 21
Value of y: 33
After Swap:
Value of x: 33
Value of y: 21
[/java]```

#HappyCoding

## 3 thoughts on “Frequently Asked Java Program 05: Swap two integer variables without using third variable”

1. Cecil Tom says:

Try with XOR option too as + may result in overflow –
a=a^b ; ( a XOR B)
b=a^b; ( a XOR B)
a=a^b; ( a XOR B)

=====================

1 XOR 0 = 1
0 XOR 1= 1
0 XOR 0 = 0
1 XOR 1 =0

2. Sathiyasheelan says:

Good work

3. RANJAN V says:

Nice..)))