1

When people say that objects are passed by value, do they mean that the reference of the object is copied and "passed by value"? I've been searching through YouTube and StackOverflow for hours, and haven't gotten a clear source that says so. For example, when you pass an object by value, does that mean that you are actually passing a copy of the object that has the same memory code/reference? I don't know if I'm thinking about this the correct way so please let me know if there's anything that I'm misunderstanding.

  • 4
    https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1 – 23k Mar 09 '21 at 01:34
  • 1
    The _reference_ to the object is passed by value, so the called method cannot update that reference to point to some other object, but the object that is _referred to_ by that reference can be mutated (changed) by the called method if the object is mutable. – Stephen P Mar 09 '21 at 01:34
  • Yes, the reference is copied, not the object itself. – markspace Mar 09 '21 at 01:35
  • 1
    Short answer yes. This answer has some visual diagrams that do a great job explaining how it works: https://stackoverflow.com/a/12429953/1270000 – sorifiend Mar 09 '21 at 01:35
  • 1
    Clarification on StephenP's comment ... The impact of Call by Value is that the "Callers" reference (for object like parameters passed in) can't change based on what happens in the method... If the object referred to is mutable - then of course the object can change - which the callers might notice - but the reference that the caller has is unchanged. Simple values - i.e. things like int, double ARE a copy - any change down in the called method does not flow back out. A good idea is to make parameters final (except where you need to change them) - that way you can't mistakenly change things. – Mr R Mar 09 '21 at 01:42
  • 2
    *"For example, when you pass an object by value, does that mean that you are actually passing a copy of the object that has the same memory code/reference?"* - If you read that carefully and think about it, what you wrote is a physical / mathematical impossibility. You cannot have two (different) objects with the same memory address / reference. They are the same object. Physically and logically. As noted, in Java you pass / copy the reference, NOT the object. – Stephen C Mar 09 '21 at 01:44
  • 'When people say that objects are passed by value' they are wrong if they are talking about Java. – user207421 Mar 09 '21 at 03:44

0 Answers0