Is Java “pass-by-reference” or “pass-by-value”?

+1 vote
972 views
asked Jan 18, 2019 by Hitesh Garg (799 points)  

When learning the concepts from other languages I learned that
if the changes on the passed parameter reflects the changes in the original object then it is pass by reference
but after reading some blogs I found out that java is pass by value although it fulfills the above criteria.
What is the real catch here?

commented May 27, 2021 by Stella Aldridge (20 points)  
I agree that Java is an only a pass-by-value programming language, so it can give you the understanding of objects via their references. It sounds a little bit weird but it should be understood as given. Value may differ depending on the object.

1 Answer

+2 votes
answered Mar 31, 2020 by fillermark (30 points)  

Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the reference to it. This is confusing to beginners. The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects.

So, when calling a method

For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive .
For objects, the pass by value is the value of the reference to the object.

...