How to swap two numbers in java without using third variable.

We can swap two numbers without using temp or third variable using the following two ways.  The following code snippet illustrates how to swap two variables without using temp variable in java.

class swapExample
{
public static void main(String arg[])
{
Swap s=new Swap();

s.swap(10,20);

}
}

Swap Method 1 :
—————–

class Swap
{
public void swap (int a, int b)
{

System.out.println(“Before swap” + ” a=”+a+ ” b=”+b);

b=a+b;
a=b-a;
b=b-a;

System.out.println(“After swap” + ” a=”+a+ ” b=”+b);

}

Swap using Method 2 :
————————-
public void swap1(int a, int b)
{

a = a ^ b;
b = b ^ a;
a = a ^ b;

System.out.println(“After swap using method 2″ + ” a=”+a+ ” b=”+b);
}

Output :

Before swap a=10 b=20
After swap using method 1 a=20 b=10
After swap using method 2 a=20 b=10

}

You may also like

Leave a Reply