# Swap two Numbers without using third variable Algorithm in Java

[11046 views] ### Problem Statement: Write a Java Program to Swap two numbers without using a Third Variable

For eg.
Input: a=24 b=36
Output: a=36 b=24

#### Swapping Using Arithmetic Operators

Algorithm Or Pseudocode to Swap two Number without using Third or Temporary variable Using Arithmetic Operators ##### swapWithoutVariable.java
import java.util.Scanner; public class swapWithoutVariable{ public static void main(String[] args){ int a,b; Scanner sc=new Scanner(System.in); a=sc.nextInt(); b=sc.nextInt(); a=a+b; b=a-b; a=a-b; System.out.println("a= "+a); System.out.println("b= "+b); } }

Consider a=10 and b=20. In this program, the first variable is first added to the second variable and stored in the first variable. Then the second variable is subtracted from the first variable and stored in the second variable. Lastly, the value of the 2nd variable is subtracted from 1st and stored in the first variable. This is how the values of one variable get swapped to another and vice versa, i.e. a becomes 20 and b becomes 10.

#### Swapping Using Bitwise XOR

Algorithm Or Pseudocode to Swap two Number without using Third or Temp variable Using Bitwise XOR ##### swapWithoutVariable2.java
import java.util.Scanner; public class swapWithoutVariable2{ public static void main(String[] args){ int a,b; Scanner sc=new Scanner(System.in); a=sc.nextInt(); b=sc.nextInt(); a=a^b; b=a^b; a=a^b; System.out.println("a= "+a); System.out.println("b= "+b); } }

### Want to Clear Java Interview? Read Java Interview Notes prepared by Us

#### Are You Good enough in Java?

##### Below Offers ends in   