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

0 votes
asked Jan 18, 2019 by Hitesh Garg (355 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?

1 Answer

+1 vote
answered Mar 31 by fillermark (20 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.

Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.