How to swap two numbers without using temporary variables in java

In this post, we will see how to swap two numbers without using temporary variables.
There are three ways to do it.
Java program:

package org.arpit.java2blog;
class SwapingTwoNumbers {

    public static void main(String args[]){
        int a = 5;
        int b = 10;

        // First way
        System.out.println("First way");
        System.out.println("Before swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        a = a+b;
        b = a-b;
        a = a-b;
        System.out.println("After swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

 // Second way 
 System.out.println("****************");
        System.out.println("Second way");
        System.out.println("Before swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        a = a*b;
        b = a/b;
        a = a/b;
        
        System.out.println("After swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        //Third way
 System.out.println("****************");
        System.out.println("Third way");
        System.out.println("Before swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        a = a^b;
        b = a^b;
        a = a^b;
        System.out.println("After swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);    }
}
When you run above program, you will get following output:
First way
Before swap:
a value: 5
b value: 10

After swap:
a value: 10
b value: 5

****************

Second way
Before swap:
a value: 10
b value: 5

After swap:
a value: 5
b value: 10

****************

Third way
Before swap:
a value: 5
b value: 10

After swap:
a value: 10
b value: 5

Third way is fastest of all.
Please go through Interview programs in java  for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012