r/javahelp • u/JustDudeFromPoland • 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
52
u/dr_boom Intermediate Brewer Oct 19 '22
Imagine at an office you have a bunch of folders full of information. You need to get the information to your coworker.
Pass by value means that when you give the information to your coworker, you make a copy of everything in the folder and give them a new folder.
Pass by reference means you give them a note saying "the information is in the purple folder on the third shelf." This is called a pointer - the note points to where the information is. This is also where the null pointer reference error comes from.
With pass by value, if your coworker makes any changes, it doesn't affect your folder in any way.
With pass by reference, your coworker will find your folder, and if they make a change in the folder, your data will be different!