Java Parameter Passing: Value vs. Reference
In Java, parameter passing semantics differ from languages like C#, where the "ref" keyword explicitly indicates reference passing.
Confusion Surrounding Reference Passing
Java's "pass-by-value" nature confuses developers because parameters of reference types (like objects) are actually passed by reference. However, this "reference" is simply the memory location of the object, not the object itself.
Demonstration of Value Passing
Consider the following code snippet:
Object o = "Hello"; mutate(o); System.out.println(o); private void mutate(Object o) { o = "Goodbye"; }
This code will print "Hello" to the console because the "o" parameter in the mutate method actually refers to a copy of the original reference. Assigning a new value to this copy has no effect on the original object's value.
Alternative Options for Reference Modification
To modify the original object, there are two options:
AtomicReference<Object> ref = new AtomicReference<Object>("Hello"); mutate(ref); System.out.println(ref.get()); // Goodbye! private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }
The above is the detailed content of Is Java's Parameter Passing Truly Pass-by-Value, or is it More Nuanced?. For more information, please follow other related articles on the PHP Chinese website!