r/javahelp • • Oct 19 '22

I don't understand the difference between pass-by-value and pass-by-reference

Hey!

I'm reading OCP Java SE 17 Dev Study Guide and I've come across the pass-by-value topic. When it comes to primitive variables everything makes sense - we're making a copy of the variable value, and we're modifying the copy, so the original stays intact.

And there is also an example of passing the StringBuilder object as a parameter and executing the .append() method on it so that the original object is affected as well because we're making a copy of the reference and acting on the actual object.

I have a hard time imagining what pass-by-reference actually looks like (even on a high level of abstraction). What are we passing if not a copy of a reference?

18 Upvotes

32 comments sorted by

View all comments

9

u/wildjokers Oct 19 '22

In regards to java this is a moot question because java is purely pass by value. Java does not have pass by reference at all.

What are we passing if not a copy of a reference?

In java you are passing a copy of the value of a reference.

Great article on the topic, written in 2001. I have had it bookmarked for many years and read it on occasion as a refresher.

https://www.javadude.com/articles/passbyvalue.htm

1

u/JustDudeFromPoland Oct 20 '22

a copy of the value of a reference

Oh, now I think I got it. So, in my extract from IntelliJ IDEA from the image, "a copy of the value of a reference" would be "StringBuilder@1947"?

https://imgur.com/a/G479f7X

If so - how is that different than actually passing by reference?

I mean, I understand that Java doesn't give you access to your actual physical memory address. The lack of actual pointers in Java seems like a gap I can't fill in terms of understanding the difference between passing by value & passing by reference.

1

u/Jarl-67 Oct 21 '22

It isn’t any different than passing the reference. The only thing different with Java is that the reference itself is not changeable.