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?
9
u/wildjokers Oct 19 '22
In regards to java this is a moot question because java is purely pass by value. Java does not have pass by reference at all.
What are we passing if not a copy of a reference?
In java you are passing a copy of the value of a reference.
Great article on the topic, written in 2001. I have had it bookmarked for many years and read it on occasion as a refresher.
1
u/JustDudeFromPoland Oct 20 '22
a copy of the value of a reference
Oh, now I think I got it. So, in my extract from IntelliJ IDEA from the image, "a copy of the value of a reference" would be "StringBuilder@1947"?
If so - how is that different than actually passing by reference?
I mean, I understand that Java doesn't give you access to your actual physical memory address. The lack of actual pointers in Java seems like a gap I can't fill in terms of understanding the difference between passing by value & passing by reference.
1
u/Jarl-67 Oct 21 '22
It isn’t any different than passing the reference. The only thing different with Java is that the reference itself is not changeable.
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!
16
4
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 11
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
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?
2
u/Jarl-67 Oct 21 '22
Only the reference or memory address is passed in the parameter list. The original object is NOT copied in Java.
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
1
u/dr_boom Intermediate Brewer Oct 21 '22
Fair point - in Java, they can cross out their note and write "yellow folder on the second shelf" and your note still points to the purple folder.
1
5
u/m1ss1ontomars2k4 Oct 19 '22 edited Oct 19 '22
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?
You are having trouble imagining it because you can't actually pass by reference in Java.
C++ supports pass by reference using special syntax to do so. The canonical test of whether you can pass by reference in a language is whether you can write a swap function. Consider this pseudocode:
void swap(MyType a, MyType b) {
MyType tmp = a;
a = b;
b = tmp;
}
void callSwap() {
MyType a, b;
swap(a, b);
}Obviously, this will never work if MyType is int. This is true in Java and it is true in C++. It will also never work if MyType is java.lang.Object or any subclass. So, this swap function will never work in Java. It simply cannot.
C++ is different. In C++, you simply change MyType to MyType& in the signature of swap (i.e. make it swap(MyType& a, MyType& b)), and now callSwap can actually swap its variables a and b purely by calling swap. This is "pass by reference", and MyType& is called "a reference to a MyType".
In reality, Java is always pass by value, and for non-primitive types, the value is a pointer/reference to an object.
In Java, you do not "give them a note saying 'the information is in the purple folder on the third shelf.'" You give them a copy of a note. Only a copy. No matter what happens to the note, the original note is still in your possession. They can change the contents of the folder freely or change their copy of the note freely, but once they are done, your original note is still the same note it's always been.
In C++, for pass by reference, you share the original note with them, and they can change the note to read something else. They don't give it back to you because you never gave it to them; you only shared it. So maybe you told them to look at a purple folder, but instead, they rewrote your note and now you are looking at a green folder. There's no way to write code like this in Java. You always give away a copy of the note. You never share the original note. Actually, at my company, we typically do not use pass-by-reference for anything in C++ because it isn't very practical, other than for writing swap functions, which are not very useful either.
Additional discussion: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value
2
u/maethor Oct 20 '22
In C++
I think that's the source of confusion - I think a lot of people originally viewed Java as "objects are passed by reference" (because objects are reference values) but then the C++ people chimed in with "those words don't mean what you think they mean, you're passing the value of the reference and not the reference itself" even though "passing the reference itself" is completely meaningless in Java.
I'm 99.9% certain that if I went down to my parents house and dug up my old intro to Java books from the late 90s, most (if not all) of them would claim that Java is pass by reference.
-1
u/Jarl-67 Oct 20 '22
Except this isn’t correct what you are saying. The reference itself is pass by value but any changes to the object being referred to will propagate past the method call. The contents of your ‘Note’ can be changed in Java.
1
u/darksounds Extreme Brewer Oct 20 '22
You need to be more specific and more accurate. You can't just say "this isn't correct" in response to a post that contains zero errors.
0
u/amfa Oct 20 '22
The contents of your ‘Note’ can be changed in Java.
No the "note" only contains a reference to an object.
You can change this object but not the note itself.
1
1
u/Eddy67716 Oct 20 '22 edited Oct 20 '22
Usually things that use the new keyword 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 new keyword 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).
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.
1
u/Jarl-67 Oct 21 '22
A great visual for pass by reference and pass by value.
Java behaves like the one on the left but is often identified as the one on the right.
1
u/arghvark Oct 21 '22
I'm going to try to explain this a different way.
I think the confusion comes from attempting to explain how Java behaves with terminology that is fine in formal computer science contexts, and will help explain how Java behaves to people who can or WHO ALREADY DO understand that terminology, but just gets confusing for people attempting to learn how to program, in Java, and want to know how Java works, not what the computer science terminology behind it is. So I'm going to explain the behavior first, then show the terminology being applied to it.
Parameter passing in Java comes in two flavors. The first flavor is the passing of primitives, with ints being the simplest to understand. When you have a variable of type int and you pass it to a method, the method gets its own copy of an int with the caller's value. So if we have
// ...
int i = 3;
boolean b = testInt(i);
// ...
private boolean testInt(int testValue)
{
// ...
}The testInt() method will get the value of 3, in an int named testValue; any changes made to testValue within the testInt() method will not be reflected in i, because testInt has its own copy of that (primitive) parameter.
The second flavor of passing parameters to methods is used for objects (which is everything except the primitives); let us say you have a StudentRecord class that you are going to pass to a method, and code something like the following:
// ...
StudentRecord testRecord;
fillRecord(testRecord);
// ...
private void fillRecord(StudentRecord record)
{
...
}Perhaps fillRecord() is a method that fills up the student record with information. Any changes made to record in fillRecord are also being made (at the same time) to testRecord in the method that calls fillRecord. There is only one copy of the record in this example.
The first flavor of this is called "pass by value", meaning that only the int value is passed into the called method, and there is no way for the called method to influence the value that the caller has.
The second flavor is usually called "pass by reference", meaning that the called method gets a "reference" to the variable that is in the caller, and can therefore change the value the caller has (there is an exception to this: there are objects which are immutable and can NOT be changed, but few user-written classes are like that. String is, though).
There is something the called method can NOT do however -- it cannot change the reference that the caller is using. Expanding our example:
// ...
StudentRecord testRecord;
fillRecord(testRecord);
// ...
private void fillRecord(StudentRecord record)
{
StudentRecord newRecord = new StudentRecord();
// ... many statements, filling in newRecord
record = newRecord; // <-- probably doesn't do what you want
}Here, the fillRecord() method is assigning a StudentRecord object to its copy of the reference to record. There's nothing wrong with this, and it throws no error, but it does NOT change the testRecord reference in the caller. There is no way to do that in Java to a parameter passed into a method. The called method can use dot-notation to change (public) variables in the passed-in object, and it can call methods on the passed-in object that will change data in the object, but it cannot cause the caller to get a different object reference into the variable that the caller passed in.
If the called method returned a variable, that returned variable could be assigned to an object in the caller.
I think this might be clearer to novice programmers learning Java as a first programming language. Comments, especially from people in this category, are welcome.
0
u/DahDitDit-DitDah Oct 20 '22
Pass by value: your buddy shares his online bank statement.
Pass by reference: he shares the username/password to his online bank account.
•
u/AutoModerator Oct 19 '22
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.