Home >Backend Development >C++ >Is Java Pass-by-Value or Pass-by-Reference?

Is Java Pass-by-Value or Pass-by-Reference?

Susan Sarandon
Susan SarandonOriginal
2024-12-31 16:18:10417browse

Is Java Pass-by-Value or Pass-by-Reference?

Understanding Java's Pass-by-Value Semantics

In Java, all parameters are passed by value, including reference types. This means that the actual value of the reference, not the reference itself, is passed to the method. This can be confusing since it appears that references are passed by reference because any changes made to the object referenced by the parameter will be reflected in the original object.

However, this is not true pass-by-reference behavior. The following example demonstrates this:

Object o = "Hello";
mutate(o);
System.out.println(o);

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

After executing this code, the output will be "Hello." This is because the mutate method receives a copy of the reference to the original object, not the original object itself. When the line o = "Goodbye" is executed, it changes the reference variable o inside the mutate method, but does not affect the original o variable outside the method.

To achieve true pass-by-reference behavior, one option is to use an explicit reference as follows:

AtomicReference<Object> ref = new AtomicReference<>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

In this case, the AtomicReference wrapper holds a reference to the original object. When the mutate method receives the ref parameter, it has direct access to the original object and any changes made to the object will be reflected in the original object outside the method.

The above is the detailed content of Is Java Pass-by-Value or Pass-by-Reference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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