Program 9.5: An Incorrect Swapping Algorithm

Consider the following problem. You want to swap the value of a and b. Many novices propose something like program 9.5 as the solution.

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 = 2
That 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.


Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home