Home > Java > javaTutorial > body text

Does Java Pass Objects by Value or by Reference?

DDD
Release: 2024-11-16 16:17:02
Original
363 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template