# Swap two numbers without using extra variable

Objective:  Write an algorithm to swap two numbers without using extra variable.

This is fun puzzle which is asked in the interview.

Approach:

Example:

```a = 3, b = 5
a = a + b = 8
b = a – b = 8 – 5 = 3
a = a – b = 8 – 3 = 5
Now a = 5, b = 3
```

Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

 public class SwapNumbers { public static void swap(int a, int b){ System.out.println("first number: " + a + " second number: " + b); a = a + b; b = a – b; a = a – b; System.out.println("After Swappng: first number: " + a + " second number: " + b); } public static void main(String[] args) { int a = 3; int b = 5; swap(a,b); } }

Output:

```first number: 3 second number: 5
After Swapping: first number: 5 second number: 3
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.