Wednesday, 7 October 2015

Java - Swapping values within Object

package passing_32_blog;

public class Pass {

public static void main(String[] args) {
// TODO Auto-generated method stub
First obj1 = new First(10,20);
First obj2 = new First(30,40);
System.out.println("The values before swap are " +obj1.i+"\t" +obj1.j);
obj2.swap(obj1);
System.out.println("The values after swap are " +obj1.i+"\t" +obj1.j);
}
}


package passing_32_blog;

public class First {
int i,j;
First (int k,int l){
i=k;
j=l;
}
void swap(First s){
int temp;
temp = s.i;
s.i=s.j;
s.j=temp;
}
}

Output:-
The values before swap are 10 20
The values after swap are    20 10

No comments:

Post a Comment