1

I just want to clarify something. Why is person1 and person2 still referring to the same object?

class Person{
private String name;
Person(String newName) {
name = newName;
}
public String getName() {
return name;
}
public void setName(String val) {
name = val;
}
}

class Test {
public static void swap(Person p1, Person p2) {
Person temp = p1;
p1 = p2;
p2 = temp;
}
public static void main(String args[]) {
Person person1 = new Person("John");
Person person2 = new Person("Paul");
System.out.println(person1.getName()+ ":" + person2.getName());

swap(person1, person2);

System.out.println(person1.getName()+ ":" + person2.getName());

}
}

Output would be:

John:Paul
John:Paul

I was wondering why John and Paul didn't swap?

Dex
  • 23
  • 4
  • 1
    Object references are passed by value. When you swap the values of `p1` and `p2`, `person1` and `person2` are not changed. – Radiodef May 29 '15 at 03:42

1 Answers1

1

Java is not pass-by-reference.

This means that there is no way you can swap the contents of variables in the caller's scope from within a method.

All you have been doing is exchanging the contents of the local variables p1 and p2 inside of your swap method. This has no effect on variables in main.

Note that this "problem" exists only for (local) variables. You can of course swap instance fields of an object around, and that will be visible to anyone else who happens to have a reference to the same object instance.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • So are you saying that person1 will forever hold the value "John" and person2 "Paul" unless I alter it? – Dex May 29 '15 at 03:46
  • Yes. "You" (as the `main` method) are the only one who can access your local variables `person1` and `person2`. Only you can re-assign them. But a method could change John's name to something else. – Thilo May 29 '15 at 03:48
  • So if that's the case, method swap didn't really do anything because Java is not pass-by-reference. Am I saying it right? – Dex May 29 '15 at 03:57
  • Yes, it does not have any visible effect to outside code. – Thilo May 29 '15 at 05:24