Home > DeveloperSection > Forums > Is Java “pass-by-reference” or “pass-by-value”?
Royce Roy
Royce Roy

Total Post:134

Posted on    May-01-2015 11:58 PM

 Java Java 

 1 Reply(s)
 467  View(s)
Rate this:

I always thought Java was pass-by-reference; however I've seen a couple of blog posts (for example, this blog) that claim it's not. I don't think I understand the distinction they're making.

What is the explanation?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    May-02-2015 6:09 AM

Java is always pass by value, with no exceptions, ever.

So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? 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. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.

So, when calling a method

For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).
For objects, the pass by value is the value of the reference to the object.
So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.

Naturally, passing by value a reference to an object looks very like (indistinguishable in practice) from passing an object by reference.

Don't want to miss updates? Please click the below button!

Follow MindStick