We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,371 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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??
2
Contributors
1
Reply
8 Minutes
Discussion Span
8 Months Ago
Last Updated
2
Views
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
Administrator
3,456 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0485 seconds using 2.55MB