Swapping
public class Student{
private String name;
public Student(String name)
{this.name=name;
}
public void setName(String sett){
name=sett;}
public String getName()
{return(name);}
}
public class Swaptest{
public static void swap(Student p,Student q){
Student temp;
temp=p;
p=q;
q=temp;
}
public static void main(String a[])
{Student s1=new Student("John");
Student s2=new Student("Mary");
swap(s1,s2);
System.out.println("s1="+s1.getName());
System.out.println("s2="+s2.getName());
}
}
Output:s1=John
s2=Mary
Why is the code not swapping names??
Related Article: Missing return statement
is a Java discussion thread by baneyramos_09 that has 10 replies and was last updated 3 months ago.
bigzos
Junior Poster in Training
64 posts since Jun 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Why is the code not swapping names??
Because you're not swapping names. You're not even swapping Students. You're swapping local references (copies of references that are passed to swap()), which ultimately doesn't change the original references.
deceptikon
Challenge Accepted
3,456 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57