Program 9.6: A Correct Swapping Algorithm

class Swap2 {

  public static void main(String args[]) {
  
   int a = 1;
   int b = 2;
   int temp;
   
   System.out.println("a = " + a);
   System.out.println("b = " + b);
   
   // swap a and b
   
   temp = a;
   a = b;
   b = temp;
   
   System.out.println("a = " + a);
   System.out.println("b = " + b);   
  
  }

}

This program produces the output you expect:

a = 1
b = 2
a = 2
b = 1

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