Does Java have pass by reference?
Just curious how this works in Java, seems like it isn’t like classic pass by reference in other languages like C/C++.
11 Replies
⌛
This post has been reserved for your question.
Hey @DaMango! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
Java is generally pass-by-value but it may pass references by value
With primitive data types, you have normal pass by value
but with objects, (which are located in the heap), you always have references to these objects so you are passing these references - but if you reassign them, you have a different object and this is not propagated
For example
See also https://stackoverflow.com/q/40480/10871900
when would you want to pass the references?
?
when is it advantageous to pass the object reference
err
if you're passing the reference of the object by value
you don't really get a performance benefit from doing so?
What do you mean with that?
Using references allows you to have complex/arbitrary object graphs and other structures
in c/c++ you might pass by reference to avoid the overhead of copying a variable and using it to reassign the value of the original reference
So?
You are still passing references by value
so the only thing that's copied is the reference
what situations have you passed the object reference in java?
i'm looking to learn when it might be a good idea to do it vs. when not to
Java always passes object references by value in that way
which allows you to pass objects and modify them elsewhere
it also has some disadvantages like it introducing indirections (following the reference can be a performance cost in a few ways)
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.