Thursday, September 15, 2016

 Pass by Value or Pass by Reference in Java?


Before coming to conclusion let's look at the example.

Code:
class Person {
private String name = null;

public Person() {
}

public String getName() {
return this.name;
}

public void setName(String newName) {
this.name = newName;
}
}

class Manager {
public Person changePersonName1(Person p) {
if (p != null) {
// just change only name
p.setName("I'm changed by Manager in changePersonName1()");
}
return p;
}

public Person changePersonName2(Person p) {
if (p != null) {
// just change only name
p.setName("I'm changed by Manager in changePersonName2()");
// create new Person instance, which means you no longer making any
// changes to the argument 'p' but on new Person instance
p = new Person();
p.setName("I'm recreated as new Person by Manager in changePersonName2()");
}
return p;
}
}

public class JavaPassByValueOrReference {
public static void main(String[] args) {
// Create a person
Person p1 = new Person();
p1.setName("I'm in p1 instance");

// Create a Manager
Manager mgr = new Manager();
System.out.println("0: Person p1 name = " + p1.getName());

//1-change name 
mgr.changePersonName1(p1);
System.out.println("1: Person p1 name = " + p1.getName());

//2-change name
mgr.changePersonName2(p1);
System.out.println("2: Person p1 name = " + p1.getName());
}
}
output:
0: Person p1 name = I'm in p1 instance
1: Person p1 name = I'm changed by Manager in changePersonName1()
2: Person p1 name = I'm changed by Manager in changePersonName2()

Explanation:
  1. In Main(..) method the 'Name' of Person is defaulted to "I'm in p1 instance".
  2. When Manager instance (mgr) changed the Person's name using  changePersonName1(..), the 'Name' of Person is changed from "I'm in p1 instance" to "I'm changed by Manager in changePersonName1()"
  3. When Manager instance (mgr) changed the Person's name using  changePersonName2(..), the 'Name' of Person is changed from "I'm changed by Manager in changePersonName1()" to "I'm changed by Manager in changePersonName2()"  instead of "I'm recreated as new Person by Manager in changePersonName2()"
The reason is in changePersonName2(Person p) of Manager class, the input argument (p) is reassigned to new Person instance (p = new Person()), changes to done on newly created instance are not returnable to or visible to Caller.

A copy of an object is made and passed to a function. On returning from the function, the copy is again copied back to the original passed object. So, the value set in the function is copied back.

In short 'Java is Pass the Reference By Value" or 'Pass the copy of Pointer(Reference) by Value'  or 'References are passed by Value' .

No comments:

Post a Comment