Pages

May 6, 2011

Swap Objects with Reference

SWAP EXAMPLE


In the following example we are swapping objects. Java only allows the exchange or swapping values between two objects with reference.


There are two functions created demonstrating proper and improper exchange of data.


public class swap{
 private int num;
 private String name;
 public swap(){
  num = 0;
  name = null;
 } 
 
 public swap(int n, String name){
  num = n;
  this.name = name; 
 }
 public  void improperSwap(swap a, swap b){
  swap t;
  t = a;
  a = b;
  b = t;
  System.out.println("InSide ImproperSwap");
  System.out.println(a);
  System.out.println(b); 
  System.out.println("*** Bye Swap ****\n"); 
 }
 public String toString(){
  String t;
  t = "The number is :" + num + "\n" + 
      "The name is: " + name;
     return t;
 }
 public static void main(String args[]){
  swap one , two, swapper;
  one = new swap(10,"Ashu");
  two = new swap(45,"Dennis");
  swapper = new swap();
  swapper.improperSwap(one, two);
  System.out.println(one);
  System.out.println(two);
 }
}

No comments:

Post a Comment