Swap two numbers - Java program

Q. Write a Java program to swap two numbers.

Answer:

Program to swap two numbers using a temporary variable.

Swap.java

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


Output:

swaping

Q. Program to swap two numbers without using third variable.

Answer:

SwapNumber.java

class SwapNumber
{
        public static void main(String[] args)
        {
                int a = 15;
                int b = 17;
                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);
        }
}


Output:

swap without third var