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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.