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

Show parent comments

2

u/Farpafraf Oct 20 '22

With pass by value, if your coworker makes any changes, it doesn't affect your folder in any way.

I understand what you mean but java is pass by value so this example might be confusing if someone were to think of a Folder object thinking the object itself got copied

1

u/Jarl-67 Oct 21 '22

In pass by value, the parameter would be a complete copy. Changes would not affect the original version. Java does not behave that way as the object is not copied.

1

u/Farpafraf Oct 21 '22

Java is strictly pass by value, albeit in a weird way, as you copy the reference to the object. In a language allowing pass by reference.

a = 0
f(b){
    *b = 1
}
f(*a)
print(a)
//prints 1

1

u/Jarl-67 Oct 21 '22

Again, in pass by value, the object would be copied not referenced. It isn’t that hard to understand. Watch the video, read the definitions.

1

u/Farpafraf Oct 21 '22

1

u/Jarl-67 Oct 21 '22

In ‘Pass by value’, the parameter would be a complete copy. What happens in Java?

1

u/Farpafraf Oct 21 '22

look if you made up you own definition of pass by reference and want to believe against the whole world that according to it java is pass by reference so be it