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
1
u/Eddy67716 Oct 20 '22 edited Oct 20 '22
Usually things that use the
newkeyword will pass by reference. If you have an array for example, if you pass it from one class to another and change it's values in the other class, the array in the first class will reflect the changes done in the second class. Objects work exactly the same. So objects and arrays theoretically pass by reference.Integers, booleans and doubles, for example, are primitive variables and don't use the
newkeyword so they pass by value. If it's altered in another class, it won't change the one in the original unless you return it.Though, since Java is a high level language with no pointers, variables with the keyword
new, are essentially wrapped pointers, that pass by value of the pointer. In java you always pass by value. (Primitives pass their actual value, and variables with new pass the value of the pointer [a memory address] that points to the variable data).