Thursday, 8 September 2016

Java Program to Swap Two Variables Without Using Third Variable?

Below Example shows how to swap two variables without using third variable. The Simple logic behind swapping is to add and subtract both values in given variables.

public class SwapTwoNumbersWithoutThirdVariable {

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

System.out.println("BEFORE SWAP : A = "+a+" ,B = "+b);
a = a+b;
b = a-b;
a = a-b;
System.out.println("AFTER  SWAP : A = "+a+" ,B = "+b);
}

}

Program Output :-

BEFORE SWAP : A = 12 ,B = 6

AFTER  SWAP : A = 6 ,B = 12



No comments:

Post a Comment