Home >Java >javaTutorial >Does Java Pass Objects by Value or by Reference?
Java's "Pass by Value" vs. "Pass by Reference" Distinction
In Java, variables store references to objects, not the objects themselves. This distinction affects how objects are passed as arguments to methods.
Scenario A: Passing a Reference
Consider the following code snippet:
Foo myFoo; myFoo = createFoo(); public Foo createFoo() { Foo foo = new Foo(); return foo; }
When myFoo is assigned the result of createFoo(), a new Foo object is created and assigned to foo. The reference variable myFoo now points to this new object. If myFoo is subsequently modified, the changes will affect the original Foo object. However, if a new reference variable is assigned to myFoo, it will point to a different object.
Scenario B: Passing a Value
Contrast this with the following:
Foo myFoo; createFoo(myFoo); public void createFoo(Foo foo) { Foo f = new Foo(); foo = f; }
In this case, the method createFoo() receives a reference to myFoo. However, within the method, a new Foo object is created and assigned to a local reference variable f. The line foo = f only changes the reference within the method, not the reference stored in the calling method. Therefore, any modifications made to foo in the method will not be reflected in the original Foo object.
Conclusion
Based on these examples, it's evident that Java always passes arguments by value, not by reference. The value passed is a reference to the object, not the object itself. Consequently, changes made to reference variables within methods do not affect the original objects. However, changes made to the object itself through the reference will be reflected in the original object.
The above is the detailed content of Does Java Pass Objects by Value or by Reference?. For more information, please follow other related articles on the PHP Chinese website!