Tuesday, July 27, 2021

Pass by value and Pass by reference in Java

Java is always pass by value, when we say it is pass by value means it creates copy and pass the copy not the original one.

Lets a example:

public class B {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public B(String id, String name) {
this.id=id;
this.name=name;
}
}

public class A {

public static void main(String args[]) {

B b = new B("1", "one");

A a = new A();

System.out.println("Befor id : " + b.getId() + "name :" + b.getName());

a.changeValue(b);

System.out.println("After id : " + b.getId() + "name :" + b.getName());

}

private void changeValue(B copy) {

copy.setId("2");

copy.setName("two");

}

}

Now when we pass the reference variable like this a.changeValue(b); 
actually we are creating the copy of reference variable value like this 











As you can see actually we are creating the copy and passing its value to new reference which is pass by value.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home