Win a 3 month subscription to Marco Behler Videos this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

passing by reference or by value?  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 380
3
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read somewhere that Java only passes by value but how come when I run this code after I called the method the number use is still the value 20 after the method is called even though in the method I altered the value that was passed in if Java passed by value wouldn't it have changed use after the method was done?








this also happens when I try to change a String I start of with an original String then in the change method I alter the String but then again after I pass the String into the method when printed it still appears with the original String,how come this is happening?


thanks
 
Adam Chalkley
Ranch Hand
Posts: 380
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry I meant to say the value 10
 
Campbell Ritchie
Marshal
Posts: 54909
155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, doesn't that show pass‑by‑value? You have a value in the main method and that value is copied into the parameter. Altering the parameter (which is usually not good practice in production code) doesn't alter the original value in main.
Change the name of the parameter in the change method to i and you will see no change in the behaviour. You will however have two variables of different names, which will make it clear that the two variables are independent of each other.
 
Norm Radder
Rancher
Posts: 2052
26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try changing line 8 to:
 
vayne nick
Greenhorn
Posts: 1
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Spec says that everything in Java is pass-by-value . There is no such thing as "pass-by-reference" in Java. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners . Check t his example...java pass by value

Nick
 
Junilu Lacar
Sheriff
Posts: 10929
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vayne nick wrote:Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners


Welcome to the Ranch, vayne nick. Being confused comes with the territory of being a beginner in anything. Saying "when we pass the value of an object, we are passing the reference to it" isn't exactly the epitome of clarity either, especially in the context of differentiating between a "value" vs. a "reference". I believe one of the motivations for using the word "reference" was to differentiate it from the term "pointer" and what that implies for folks who have programmed in languages like C and C++. The main difference between a Java reference and a C-like pointer is that you can't perform arithmetic on a reference as you can with a pointer. You can't increment a reference to point to a different location in memory.
 
Henry Wong
author
Sheriff
Posts: 23260
124
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Saying "when we pass the value of an object, we are passing the reference to it" isn't exactly the epitome of clarity either, especially in the context of differentiating between a "value" vs. a "reference". I believe one of the motivations for using the word "reference" was to differentiate it from the term "pointer" and what that implies for folks who have programmed in languages like C and C++. The main difference between a Java reference and a C-like pointer is that you can't perform arithmetic on a reference as you can with a pointer. You can't increment a reference to point to a different location in memory.


For those who come from a C++ background, this term is further confusing. Pass by value means an implicit call to the object's copy constructor, and hence, a copy of the instance is provided to the caller. And pass by reference means pointers are used, so hence, changes to the parameter variable will also change the caller's variables too.  Java doesn't do either of those.

Henry
 
Campbell Ritchie
Marshal
Posts: 54909
155
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vayne nick wrote:The Java Spec says that everything in Java is pass-by-value . . . .
Welcome to the Ranch again
Please tell us which section in the Specification says that; I can never seem to find that bit.
Check t his example...java pass by value

Nick
I am afraid I think that tutorial is poor quality and not clear. It shows the two names not changing but doesn't explain how that phenomenon would differ between pass‑by‑value and pass‑by‑reference.

[Addition]Sorry for the delay in replying; I have been away most of the day.
 
Ryan McGuire
Ranch Hand
Posts: 1134
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this...

Java isn't passing objects by-reference - it's passing object references by-value.

I understand what Java is doing, so I don't need that explained.  HOWEVER, even though I just used the two terms above, I still fail to see the difference between passing an object by reference and passing an object reference by value.  In both cases aren't you just passing a reference to an object?
 
Campbell Ritchie
Marshal
Posts: 54909
155
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the case of pass‑by‑value, line 3 will print xyz because the assignment in line 6 is applied to something distant.
In the case of pass‑by‑reference, line 3 will print pqr because the assignment in line 6 is applied to the same thing.

Neither Java® nor C supports pass‑by‑reference, but it is possible to mimic pass‑by‑reference in C.
If given the appropriate form of instructions, C++ supports pass‑by‑reference.
 
Liutauras Vilda
Marshal
Posts: 4270
256
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@OP

You code wouldn't compile because you have method change(int x) declared within something else named change().
On top of that you have poor formatting and indentation. Basically a mess in 15 effective lines of code.
 
Junilu Lacar
Sheriff
Posts: 10929
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McGuire wrote:I still fail to see the difference between passing an object by reference and passing an object reference by value.  In both cases aren't you just passing a reference to an object?

The difference is that the actual parameter doesn't get changed when passing by value whereas it does when passing by reference. For example:


After the call to foo(bar) is made on line 7, the bar variable declared on line 6 would reference the Bar object created on line 2 if Java did pass-by-reference. Since this does not happen in Java because all parameters are passed by value instead, the bar variable will still reference the Bar object created on line 6 after the method call on line 7.  The fact that you can alter the Bar object created on line 6 via the formal parameter b of method foo() is irrelevant to pass-by-reference vs. pass-by-value semantics. 

In short, pass-by-reference means that any change to the formal parameter affects the actual parameter.  When passing object references, the parameter is the reference, not the object being referenced.
 
Adam Chalkley
Ranch Hand
Posts: 380
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys much appreciated for all the input makes sense now =)
 
Ryan McGuire
Ranch Hand
Posts: 1134
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:In the case of pass‑by‑value, line 3 will print xyz because the assignment in line 6 is applied to something distant.
In the case of pass‑by‑reference, line 3 will print pqr because the assignment in line 6 is applied to the same thing.

Neither Java® nor C supports pass‑by‑reference, but it is possible to mimic pass‑by‑reference in C.
If given the appropriate form of instructions, C++ supports pass‑by‑reference.


I 100% understand how that works -- I'm just having issue with the terminology.

Obviously, Java doesn't pass objects by-value.  Instead it passes a reference to an object.



This will print "Mango".  This is because a reference to the object created in line 1 is being passed tot he method, right?  So if the method is passed a reference to the object, why is it correct to say that the object reference is being passed by-value but NOT that the object is being passed by=reference?  Just reiterating the rule that Java is pass by-value only does not answer the question.  What is the difference between passing a reference to an object and passing an object by reference?  What can you do in either case that you can't in the other?
 
Ryan McGuire
Ranch Hand
Posts: 1134
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:
Ryan McGuire wrote:I still fail to see the difference between passing an object by reference and passing an object reference by value.  In both cases aren't you just passing a reference to an object?

The difference is that the actual parameter doesn't get changed when passing by value whereas it does when passing by reference. For example:


After the call to foo(bar) is made on line 7, the bar variable declared on line 6 would reference the Bar object created on line 2 if Java did pass-by-reference. Since this does not happen in Java because all parameters are passed by value instead, the bar variable will still reference the Bar object created on line 6 after the method call on line 7.  The fact that you can alter the Bar object created on line 6 via the formal parameter b of method foo() is irrelevant to pass-by-reference vs. pass-by-value semantics. 

In short, pass-by-reference means that any change to the formal parameter affects the actual parameter.  When passing object references, the parameter is the reference, not the object being referenced.


If 'b' of type Bar is the parameter to method foo(), you can indeed change that Object.  If the body of foo() looked like this...



1. Doesn't that change the object that was passed to foo()?
2, Therefore isn't the object being passed by reference?

Of course in your original foo(), assigning a new value to the b doesn't have any effect in the client code, that would mean that the object reference was passed by reference.  So if an object reference is passed by value, isn't that the same thing as passing the underlying object by reference?
 
Henry Wong
author
Sheriff
Posts: 23260
124
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McGuire wrote:Just reiterating the rule that Java is pass by-value only does not answer the question.  What is the difference between passing a reference to an object and passing an object by reference?  What can you do in either case that you can't in the other?


I don't think you are wrong here... nor is it correct to be that pedantic. With Java, it's pass by value *and* we all know what you mean...

The argument, which I made, isn't to say what it is. It is simply that those coming from C++ have a different meaning for "pass by reference" and "pass by value", that is different from Java... but ... in that context, with C++, pass by reference, means that if you change the variable, the calling variable will also change. In Java, changing the reference variable has no affect on the caller.

Henry
 
Liutauras Vilda
Marshal
Posts: 4270
256
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McGuire wrote:


1. Doesn't that change the object that was passed to foo()?

Of course it does (assuming height field is accessible).

But look what Henry highlighted
Henry Wong wrote:In Java, changing the reference variable has no affect on the caller.


So, Ryan, yours case and Henry's situations are different. You are changing objects state, while Henry saying, that changing reference variable has no effect. Reference variable in your case is 'b'. So you don't do anything with 'b', but rather with object, to which 'b' is refering to.
 
Junilu Lacar
Sheriff
Posts: 10929
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe if you think of it more technically, in terms of the stack. When a method is called, the parameter values are pushed on the stack. For primitive types, a copy of the primitive values is pushed. For object references, a copy of the reference is pushed, not a copy of the object. So, no, pushing a copy of the reference is NOT the same as pushing the object itself unto the stack.

As I said before, the fact that you can manipulate the same object in memory via an object reference passed to the formal parameter has no relevance to the pass-by-value vs by-reference semantics. It's not about being able to change the object being referenced, it's about being able to change the reference itself.
 
Campbell Ritchie
Marshal
Posts: 54909
155
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McGuire wrote:. . . This will print "Mango".  This is because a reference to the object created in line 1 is being passed tot he method, right?  So if the method is passed a reference to the object, why is it correct to say that the object reference is being passed by-value but NOT that the object is being passed by=reference?
That object is mutable, and you can change its state, so it changes from Banana to Mango. It is the same object, but its contents can be changed. That is different (as you already know) from exchanging one object for another.
You can only pass the value of the reference; you are passing an instruction to find the memory location of the object. You are telling the method, “This is where you can find the Banana,” rather than the whole of the banana. You cannot pass the actual object for at least two reasons:-
  • 1: It will occupy too much space on the stack (somebody mentioned the stack after that post). If you pass the memory location (directly or indirectly) you will occupy 4 or 8 bytes on the stack depending on whether you have a 32‑bit machine or a 64‑bit machine. If you pass the whole object, you risk slower execution and overwhelming the space available for the stack.
  • 2: The size of the reference is predictable; the size of the object isn't. If you put the reference on the stack, you know it will occupy 4 or 8 bytes; you cannot predict the size of the object in advance because Banana and Mango occupy slightly different amounts of memory.
  •   Just reiterating the rule that Java is pass by-value only does not answer the question.  What is the difference between passing a reference to an object and passing an object by reference?  What can you do in either case that you can't in the other?
    I see that sort of problem all the time; people don't learn the jargon. Jargon can be confusing to start with, but if used correctly it is very precise and concise. The difference between passing a reference and by reference is significant. It might be better to say you are passing a copy of the reference.

    What you are doing is putting a number onto the stack representing the location of your banana. That is the reference to the banana fruit. Then you are changing the contents of that location to mango. You have now changed the state of that object. You will find a banana String on the heap somewhere (or you won't find it because you can't directly explore the contents of the heap, but it is there). There is also a mango String on the heap, and the current fruit object has its name field changed from pointing to banana to mango. But your reference still points to the same object. So far so good; you have still got the same number representing a memory location on the stack.
    Then what you are doing is change that memory location. You are replacing the location of the mango with a different location which is papaya. But (if we use pass‑by‑value) all other numbers representing the mango still point to mango. Pass‑by‑value means the change of the value on the stack is restricted to one place: line 9. It means the a in line 3 does not reflect that changes. So line 4 prints mango.
    Pass‑by‑reference would mean that the change in line 9 would be reflected in line 3 and the value of the memory location would change in two places; line 4 would print papaya. Pass‑by‑value means any changes to whichever reference you are using are confined to line 9.
     
    Ryan McGuire
    Ranch Hand
    Posts: 1134
    8
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:What you are doing is putting a number onto the stack representing the location of your banana. That is the reference to ...


    Yup,  I have no misconceptions about how everything works.  My only concern is about the jargon used to describe it.  However, I think I have it now: It's not a question of describing the parameter passing convention, but rather one of how we refer to object variables.


    Here, 'a' isn't a SomeClass object - it's a reference to a SomeClass object.

    In an assignment like...

    ... we aren't changing SomeClass object 'a', we're changing the (otherwise anonymous) SomeClass object that 'a' references or "points to".

    Declaring a method like...

    ...doesn't mean StaticMethod() takes a SomeClass as a parameter - it takes a SomeClass reference as a parameter.  ...and that reference is passed by-value.

    So...
    Saying things like, "'a' has a 'name' field or, "the object 'a' is passed to the StaticMethod() method," is arguably wrong.  They should be, "the object that 'a' references has a 'name' field," and, "the object rerference 'a' is passed to the StaticMethod() method (by-value)."  Pretending that a is an object instead of a reference to an object is just shorthand to make conversations a bit more tractable.

    If you want to say that 'a' in the above code an object of type SomeClass, you must concede that the object 'a' is being passed to StaticClass() by-reference.  If, on the other hand, you want to blow the "Java is 100% pass-by-value" trumpet, then you have to call variables like 'a' in the code above references to objects instead of objects.  And of course you can change your level of formality depending on the context.

    Is that all reasonable?
     
    Junilu Lacar
    Sheriff
    Posts: 10929
    158
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ryan McGuire wrote:
    Is that all reasonable?

    Sounds like we're all on the same page now. 
     
    Liutauras Vilda
    Marshal
    Posts: 4270
    256
    BSD
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ryan McGuire wrote:Is that all reasonable?

    I have assigned you a cow. Actually to a user which references to your person

    Your acting in this thread was more than professional and i'm sure many will benefit from the information has been gathered after you raised the questions.
     
    Liutauras Vilda
    Marshal
    Posts: 4270
    256
    BSD
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Adam, Cowgratulations, your topic has been published in our July's Edition Journal.
     
    Dmytro Grytskiv
    Greenhorn
    Posts: 10
    1
    MySQL Database Netbeans IDE Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi everyone! I have made an example app which shows that how Java works with primary type (int), object (String) and Collection (List).



    The output in terminal:
     
    Liutauras Vilda
    Marshal
    Posts: 4270
    256
    BSD
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Dmytro Grytskiv, welcome to the Ranch.

    Fabulous indentation and formatting

    You missed one case with List's reference variable re-assignment, which I think really needs to be in that example. What happens if line 31 you set to null? var = null;

    Your called type as primary, I think would be better if were called as primitive type
     
    Dmytro Grytskiv
    Greenhorn
    Posts: 10
    1
    MySQL Database Netbeans IDE Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Liutauras Vilda wrote:Dmytro Grytskiv, welcome to the Ranch.

    Fabulous indentation and formatting

    You missed one case with List's reference variable re-assignment, which I think really needs to be in that example. What happens if line 31 you set to null? var = null;

    Your called type as primary, I think would be better if were called as primitive type


    Thank you for comments.

    Can you please give some details about indentation and formatting? I used standard NetBeans auto formatting.

    When I set to null at line 31 ()
    I have got output:


    My bad, I mean "primitive type" when said "primary type" ))
     
    Adam Chalkley
    Ranch Hand
    Posts: 380
    3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks Liutauras

    it's an honour =)
     
    Dmytro Grytskiv
    Greenhorn
    Posts: 10
    1
    MySQL Database Netbeans IDE Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Possibly this example will be better:



    Output:
     
    Liutauras Vilda
    Marshal
    Posts: 4270
    256
    BSD
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    That is indeed that
     
    Greg Sully
    Greenhorn
    Posts: 13
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    at the first I should say Thank you to all of staffs here to take yours time to explain details for us.

    I think this problem(understanding refrence/object concept)comes from the meaning of them to people like me that the native language is not English.
    my English is so bad as you can see >.< so I should try harder to understand sentences the parse it in my brain to understand whats going on!

    for example this post from Vilda save my life

    So, Ryan, yours case and Henry's situations are different. You are changing objects state, while Henry saying, that changing reference variable has no effect. Reference variable in your case is 'b'. So you don't do anything with 'b', but rather with object, to which 'b' is refering to.

    So I want to Campbell explain this if possible again

    hen what you are doing is change that memory location. You are replacing the location of the mango with a different location which is papaya. But (if we use pass‑by‑value) all other numbers representing the mango still point to mango. Pass‑by‑value means the change of the value on the stack is restricted to one place: line 9. It means the a in line 3 does not reflect that changes. So line 4 prints mango.
    Pass‑by‑reference would mean that the change in line 9 would be reflected in line 3 and the value of the memory location would change in two places; line 4 would print papaya. Pass‑by‑value means any changes to whichever reference you are using are confined to line 9.

    I cant understand why print mango instead of papaya ?

    at the end Thanks Adam Chalkley to make a thread that I cant cause of my poor language.Like your Generic problem that help me alot.
    so I wan to tell you lets go and ask more question here your questions are very close to my words that won't raise from my heart

     
    Campbell Ritchie
    Marshal
    Posts: 54909
    155
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Greg Sully wrote:. . . people like me that the native language is not English.
    It is not a problem about English; the terms pass by reference and pass by value hve specific computer science meanings which are not phrases used in ordinary English. People who have spoken English all their lives still get it wrong.
    . . . Campbell explain this if possible again
    . . .
    I cant understand why print mango instead of papaya ?
    . . .
    I think you are referring to this post.
    In line 2 the name field is set equal to Banana. Then the address of the object a is copied and sent to the method in line 3.
    sc→object1→Banana
    a→object1→Banana

    In line 8 the name field changes to Mango. If you print the object sc in the method, or the object a, both references point to the same object which will show Mango.
    sc→object1→Mango
    a→object1→Mango

    In line 9 sc is changed to a new object with Papaya (line 10).
    Because Java® uses pass by value only, a is unchanged.
    sc→object2→Papaya
    a→object1→Mango


    Changes like sc = ... inside the method do not change a in its original location.
     
    Campbell Ritchie
    Marshal
    Posts: 54909
    155
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A few minutes ago, I wrote:. . . Because Java® uses pass by value only, a is unchanged.
    sc→object2→Papaya
    a→object1→Mango

    . . .
    With pass by reference, that would be
    sc→object2→Papaya
    a→object2→Papaya
     
    Greg Sully
    Greenhorn
    Posts: 13
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    oh ... I thought when passing a refrence variable to a method,its replace with the parameter(there isnt any "sc" at all).but as you mentioned after calling we have tow variable that both point to same object ..
    and second tip to me was :




    I got it right ?
    I had some example and now I can understand them.please let me know if Im still wrong
     
    Knute Snortum
    Sheriff
    Posts: 3842
    91
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    What you've written looks correct to me.  And you executed the program to see if the results are what you predicted?
     
    Greg Sully
    Greenhorn
    Posts: 13
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Knute Snortum wrote:What you've written looks correct to me.  And you executed the program to see if the results are what you predicted?

    Thanks Knute nd Ryan McGuire too
    yes All result be as I expected .
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!