- The simple program to swap two number:
class SwapTwoInt {
public static void main(String[] args) {
int temp;
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("before swapping a and b : " + a + " " + b);
temp = a;
a = b;
b = temp;
System.out.println("after swapping a and b : " + a + " " + b);
}
}
- Use a swap function :
class SwapTwoInt1 {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("before swapping a and b : " + a + " " + b);
swap(a,b);
System.out.println("after swapping a and b : " + a + " " + b);
}
private static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
}
- SwapTwoInt2 :
class SwapTwoInt2 {
static class IntObj {
int value;
public IntObj(int i) {
value=i;
}
}
public static void main(String[] args) {
IntObj a = new IntObj(Integer.parseInt(args[0]));
IntObj b = new IntObj(Integer.parseInt(args[1]));
System.out.println("before swapping a and b : " + a.value + " " + b.value);
swap(a,b);
System.out.println("after swapping a and b : " + a.value + " " + b.value);
}
private static void swap(IntObj a, IntObj b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
}