Swap 2 Numbers

We can swap 2 numbers in different ways.

  1. Using a temp variable.
  2. Without using temp variable
  3. Using Logical operators
  4. In Single line

Example:

package com.gudla.swapnumbers;

/**
 * Created by santhosh on 26/3/17.
 */
public class SwapNumbers {

    public static void main(String[] args) {
        withTemp(10, 20);
        System.out.println("\n"+"\n");
        withoutTempSimple(10, 20);
        System.out.println("\n"+"\n");
        withLogical(10, 20);
        System.out.println("\n"+"\n");
        inSingle(10, 20);
    }

    private static void inSingle(int a, int b) {
        System.out.println("Before a value is : "+a);
        System.out.println("Before b value is : "+b);
        System.out.println("\n");
        b=(a+b)-(a=b);

        System.out.println("After a value is : "+a);
        System.out.println("After b value is : "+b);

    }

    private static void withLogical(int a, int b) {
        System.out.println("Before a value is : "+a);
        System.out.println("Before b value is : "+b);
        System.out.println("\n");
        a = a^b;
        b = a^b;
        a = a^b;
        System.out.println("After a value is : "+a);
        System.out.println("After b value is : "+b);
    }

    private static void withoutTempSimple(int a, int b) {
        System.out.println("Before a value is : "+a);
        System.out.println("Before b value is : "+b);
        System.out.println("\n");
        a = a+b;
        b = a-b;
        a = a-b;
        System.out.println("After a value is : "+a);
        System.out.println("After b value is : "+b);
    }

    private static void withTemp(int a, int b) {
        System.out.println("Before a value is : "+a);
        System.out.println("Before b value is : "+b);
        System.out.println("\n");
        int c = a;
        a = b;
        b = c;

        System.out.println("After a value is : "+a);
        System.out.println("After b value is : "+b);
    }
}

Output:

Before a value is : 10
Before b value is : 20

After a value is : 20
After b value is : 10

Before a value is : 10
Before b value is : 20

After a value is : 20
After b value is : 10

Before a value is : 10
Before b value is : 20

After a value is : 20
After b value is : 10

Before a value is : 10
Before b value is : 20

After a value is : 20
After b value is : 10

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s