class Swap1 {
public static void main(String args[]) {
int a = 1;
int b = 2;
System.out.println("a = " + a);
System.out.println("b = " + b);
// swap a and b
a = b;
b = a;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
This produces the following output:
a = 1 b = 2 a = 2 b = 2That isn't what you expected! The problem is that you lost the original value of a when you put the value of b into a. To correct this you need to introduce a third variable, temp, to hold the original value of a.