IS JAVA “PASS-BY-REFERENCE” OR “PASS-BY-VALUE”?

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
Java 
 803  View(s)
Ratings:
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?


  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Is Java “pass-by-reference” or “pass-by-value”?

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!