Possible Duplicate:
Is Java pass by reference?
public class myClass{
public static void main(String[] args){
myObject obj = new myObject("myName");
changeName(obj);
System.out.print(obj.getName()); // This prints "anotherName"
}
public static void changeName(myObject obj){
obj.setName("anotherName");
}
}
I know that Java pass by value, but why does it pass obj by reference in previous example and change it?
Java always passes arguments by value, NOT by reference. In your example, you are still passing
objby its value, not the reference itself. Inside your methodchangeName, you are assigning another (local) reference,obj, to the same object you passed it as an argument. Once you modify that reference, you are modifying the original reference,obj, which is passed as an argument.EDIT:
Let me explain this through an example:
I will explain this in steps:
1- Declaring a reference named
fof typeFooand assign it to a new object of typeFoowith an attribute"f".2- From the method side, a reference of type
Foowith a nameais declared and it’s initially assigned tonull.3- As you call the method
changeReference, the referenceawill be assigned to the object which is passed as an argument.4- Declaring a reference named
bof typeFooand assign it to a new object of typeFoowith an attribute"b".5-
a = bis re-assigning the referenceaNOTfto the object whose its attribute is"b".6- As you call
modifyReference(Foo c)method, a referencecis created and assigned to the object with attribute"f".7-
c.setAttribute("c");will change the attribute of the object that referencecpoints to it, and it’s same object that referencefpoints to it.I hope you understand now how passing objects as arguments works in Java 🙂