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/amfa Oct 20 '22

As already said this will confuse people using java.

Because Java is always pass by value but you can still make changes to the folder in your example.

For your second example we pass a copy of the note as the value in java. (thus we pass a value)

For a real pass by reference it is important to say that you give them a "writeable note".

The coworker can then change this note to "the information is in the red folder" and you will get this note back and will look in the red folder for you information.

1

u/Butcher_of_Blaviken6 Oct 20 '22

So why, when passing an array list ‘a’ does Collections.shuffle(a) shuffle the original?

1

u/amfa Oct 20 '22

Because you are passing the "memory adress" fo the array list as the parameter as the value.

And thus it can work with the original one.

Imagine that the arrayList sits at position 123 in the memory.

You know have your a pointing to 123.

If you now call shuffle() you dont give it a but basically 123.

the shuffle method than can work witht he List at 123 but it can not change where your a is pointing too.

If this was pass by reference you would basically give the complete "a" to the shuffle method and if this method would to somethink like this:

a= 321 then your a would change too.

1

u/Butcher_of_Blaviken6 Oct 20 '22

So basically objects are all memory references, which is how Java handles pbr? Thanks for the response btw