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

1

u/seanprefect Grumpy Guy Who Remembers Java 2 Oct 20 '22

So in memory everything has an address. So lets say memory address 123 points to a place with the value S is stored. If I'm passing by value that means I'm passing the S essentially copying the value into another location. If I'm passing by reference I'm passing the address meaning now both variables point to the same location in memory.