Swapping of two numbers

Swapping of two numbers

swapping two numbers by using a temporary variable

public class Swap {
  public static void main(String[] args) {
    int a=10,b=20;
    System.out.println("Before swapping: a="+a+",b="+b);
    int temp = a;
    a = b;
    b=temp;
    System.err.println("After swapping: a="+a+",b="+b);
  }
}

For example: a = 10, b=20, temp =0

\>> int temp = a

a = 10, b=20, temp=10

\>> a=b

a=20, b=20, temp=10

\>> b=temp

a=20, b=10, temp=10

Before swapping: a=10 b=20
After swapping: a=20 b=10

Swapping two numbers without using a temporary variable

public class Swap {
  public static void main(String[] args) {
    int a=10,b=20;
    System.out.println("Before swapping: a="+a+" b="+b);
    a = a+b;
    b = a-b;
    a = a-b;
    System.out.println("After swapping: a="+a+" b="+b);
  }
}

For example: a = 10, b=20

\>> a = a+b

a = 10+20 => a=30, b=20

\>> b = a-b

a=30, b=30-20 => b=10

\>> a=a-b

a=30-10 => 20, b=10

Finally, the numbers are swapped.

Before swapping: a=10 b=20
After swapping: a=20 b=10