There are different ways with which you can implement this program.Its very common question asked in interviews about swapping of two numbers so you must know all the way to do this program.
Here is the implementation below:
/**
*
*/
/**
* @author Dixit
*
*/
public class SwapNumbers {
public static void main(String args[]) {
int a = 10;
int b = 20;
swapNumbersUsingTemporaryVariable(a, b);
swapNumbersWithoutUsingTemporaryVariable(a, b);
swapNumbersUsingXOROperator(a, b);
swapNumbersUsingMuliplicationAndDivisionOperator(a, b);
}
private static void swapNumbersUsingMuliplicationAndDivisionOperator(int a,
int b) {
System.out.println("***swapNumbersUsingMuliplicationAndDivisionOperator***\n");
System.out.println("Before swap:");
System.out.println("a value: " + a);
System.out.println("b value: " + b);
b = a * b;
a = b / a;
b = b / a;
System.out.println("After swap:");
System.out.println("a value: " + a);
System.out.println("b value: " + b);
}
private static void swapNumbersUsingXOROperator(int a, int b) {
System.out.println("\n***swapNumbersUsingXOROperator***\n");
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);
}
private static void swapNumbersWithoutUsingTemporaryVariable(int a, int b) {
System.out.println("\n***swapNumbersWithoutUsingTemporaryVariable***\n");
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);
}
private static void swapNumbersUsingTemporaryVariable(int a, int b) {
System.out.println("\n***swapNumbersUsingTemporaryVariable***\n");
int temp;
System.out.println("Before swap:");
System.out.println("a value: " + a);
System.out.println("b value: " + b);
temp = a;
a = b;
b = temp;
System.out.println("After swap:");
System.out.println("a value: " + a);
System.out.println("b value: " + b);
}
}
Enjoy Coding. :)
waste of time...
ReplyDeleteplz again post the simple programs