Forums Register Login

Call By Reference Vs Call By Value

1
+Pie Number of slices to send: Send
Java always makes a copy of the argument and passes the copy. The called method has a local copy of the data. If the method changes the data it changes the copy, so the original value is not changed.

When we pass a primitive like int this make perfect sense. The method gets its own int variable, a copy of the original.

When we pass an object we have to think very precisely. The value that is copied and sent along is a reference or pointer to the object. The method gets its own copy of the pointer, but it doesn't get its own copy of the object. If the method changes its copy of the pointer to point to a different object the original pointer is not affected. If the method changes some of the attributes of the object, it changes the original object.

In short: In Java, object references are passed by value and primitive types are passed by value.

(posted by Stan James in this thread)

Other Resources:

  • http://www.javaranch.com/campfire/StoryPassBy.jsp
  • relevant section of the Java Language Specification

  • mooooooo ..... tiny ad ....
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com


    You can read but need at least 5 cow(s) to post
    This thread has been viewed 9462 times.
    Similar Threads
    Passing by value vs. reference
    passing primitive variables KB(chap3)
    Questions like these confuse me
    Pass by value vs pass by reference
    pass by reference and value
    More...

    All times above are in ranch (not your local) time.
    The current ranch time is
    Mar 28, 2024 18:01:57.