Home >Backend Development >C++ >Does Java Pass Parameters by Reference or by Value, and How Can You Achieve Reference-Like Behavior?
Passing Parameters by Reference in Java: A Clarification
Contrary to popular belief, Java does not support parameter passing by reference in the same way as C#'s ref keyword. However, this perception stems from the fact that for reference type parameters, the reference itself is passed by value.
In Java, all parameters are passed by value. When a reference type parameter is passed to a method, a copy of the reference is created. This means that changes made to the reference within the method do not affect the reference outside the method.
To illustrate this, consider the following example:
Object o = "Hello"; mutate(o); System.out.println(o); //Hello private void mutate(Object o) { o = "Goodbye"; }
The above code will print "Hello" to the console. This demonstrates that the reference o inside the mutate method is not the same as the reference outside the method.
If you want to modify the reference itself, you must use an explicit reference type parameter, such as java.util.concurrent.atomic.AtomicReference
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 ref parameter is passed by reference, and the value of the reference is modified within the mutate method. As a result, the code will print "Goodbye!" to the console.
The above is the detailed content of Does Java Pass Parameters by Reference or by Value, and How Can You Achieve Reference-Like Behavior?. For more information, please follow other related articles on the PHP Chinese website!