Wednesday, 8 January 2014

Demo program for swapping of objects

In this program we pass objects. But to swap the values we need to swap by value only.
Swapping the objects will not swap the values the object points to.

Demo: 

package date;

public class Date_Obj {

/** This is a program for swapping of objects.
* @Author Snehal
*/
int dd,mm,yy;
public Date_Obj() {
}
Date_Obj(int dt,int mth,int yr){
dd=dt;
mm=mth;
yy=yr;
}
public void swap(Date_Obj d1, Date_Obj d2) {
Date_Obj d3 = new Date_Obj();
d3.dd = d1.dd;
d3.mm = d1.mm;
d3.yy = d1.yy;

d1.dd = d2.dd;
d1.mm = d2.mm;
d1.yy = d2.yy;

d2.dd = d3.dd;
d2.mm = d3.mm;
d2.yy = d3.yy;
}
public String toString() {
return dd+" "+mm+" "+yy;
}
public static void main(String[] args) {
System.out.println("Before swap:");
Date_Obj d1 = new Date_Obj(1,1,2014);
System.out.println(d1);
Date_Obj d2 = new Date_Obj(2, 2, 2014);
System.out.println(d2);
d1.swap(d1, d2);
System.out.println("After swap:");
System.out.println(d1);
System.out.println(d2);
}

}

Output: 
Before swap:
1 1 2014
2 2 2014
After swap:
2 2 2014
1 1 2014

No comments:

Post a Comment