Java is pass by value … Always!

This is a discussion that I have had frequently, mostly with programmers that are transitioning from C/C++ where they are forced to consider how they want to pass values in and out of methods. In Java since you have no choice in the matter it is best to just let it go and rededicate that portion of your brain to a more productive task (like memorizing movie quotes or something).

For those that really want to know, Java is pass by value .. always.

First for anybody that isn’t familiar with the terms:

Pass By Reference

Passing parameters by reference means that the pointer nesting of parameters is deeper than the pointer nesting of local variables. If you have a variable with the type of a class, the variable is a pointer to the actual value.

Pass By Value

Pass by value means you are making a copy in memory of the actual parameter’s value that is passed in, a copy of the contents of the actual parameter.

I believe the key point of confusion 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.  But wait isn’t that the opposite of what you just said?No, of course not, Java objects are always accessed through a reference, rather than directly, it is commonplace to refer to fields, variables, and method arguments as being objects, when technically they are actually references to objects.  However when those references get passed through a method call you are actually passing a copy of the value of the reference, this means that inside the method call if the variable were to get reassigned that the original object would not be affected.

Let’s look at a simple example:

private void foo(Object bar) {
    bar = "Override Value";
}

public static void main(String[] args) {
    String baz = "Original Value";
    foo(baz);
    System.out.println(baz);
}

Since Java is pass by value, when calling the method foo the reference to baz is copied and passed as a value. This is why internal to the method foo, reassigning the variable has no effect once the scope has changed back to main

As a consequence of not being about to reassign object references that are passed by value, Java lacks out parameters that are found in languages like ADA and C#.