Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass parameters by reference in Java?

Tags:

java

c#

reference

I'd like semantics similar to C#'s ref keyword.

like image 546
ripper234 Avatar asked Oct 10 '22 14:10

ripper234


2 Answers

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

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

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

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

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

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }
like image 243
oxbow_lakes Avatar answered Oct 13 '22 03:10

oxbow_lakes


Can I pass parameters by reference in Java?

No.

Why ? Java has only one mode of passing arguments to methods: by value.

Note:

For primitives this is easy to understand: you get a copy of the value.

For all other you get a copy of the reference and this is called also passing by value.

It is all in this picture:

enter image description here

like image 68
PeterMmm Avatar answered Oct 13 '22 03:10

PeterMmm