|
Swap two Numbers
Swap two numbers.
|
package com.bethecoder.tutorials.coding.examples;
public class SwapTwoNumbersTest {
/**
* @param args
*/
public static void main(String[] args) {
for (int i = 1 ; i < 3 ; i ++) {
swap(i, i + 2);
swap2(i, i + 7);
swap3(i, i + 9);
System.out.println();
}
}
private static void swap(int a, int b) {
a = a + b - (b = a);
System.out.println("a : " + a + " b : " + b);
}
private static void swap2(int a, int b) {
a = a + b;
b = a - b;
a = a - b;
System.out.println("a : " + a + " b : " + b);
}
private static void swap3(int a, int b) {
int temp = b;
b = a;
a = temp;
System.out.println("a : " + a + " b : " + b);
}
}
|
| |
It gives the following output,
a : 3 b : 1
a : 8 b : 1
a : 10 b : 1
a : 4 b : 2
a : 9 b : 2
a : 11 b : 2
|
|