Home >Backend Development >C++ >Does Java Pass Parameters by Reference or by Value?
Passing Parameters by Reference in Java
In Java, every parameter is passed by value, which may seem counterintuitive, especially if you're coming from languages like C# that support pass-by-reference. However, the semantics are slightly different under the hood.
How Java Handles Reference Types
For parameters of reference type (such as objects), Java does pass the reference itself by value. Therefore, it appears to be pass-by-reference, as assignments within the method affect the reference outside the method.
However, it's important to note that the reference passed is not the same as the reference used in the calling method.
Proof of Pass-by-Value
Consider the following example:
Object o = "Hello"; mutate(o); System.out.println(o); private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!
This code prints "Hello" to the console, even though the mutate() method attempts to modify the o reference to "Goodbye." This demonstrates that the reference passed to mutate() is not the same as the original o reference, supporting the pass-by-value semantics.
Options for True Reference Passing
To achieve true pass-by-reference behavior, you can use the following approach:
AtomicReference<Object> ref = new AtomicReference<Object>("Hello"); mutate(ref); System.out.println(ref.get()); //Goodbye! private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }
In this case, the AtomicReference provides a wrapper around the object, and its reference is truly passed by value. Assignments to the reference within mutate() will affect the reference outside the method, resulting in the desired pass-by-reference behavior.
The above is the detailed content of Does Java Pass Parameters by Reference or by Value?. For more information, please follow other related articles on the PHP Chinese website!