Java is pass-by-value

Does the Java parameter passing follow pass-by-value or pass-by-reference semantics? For primitives, it must obviously be by value, since we don’t have any references. For objects, you can find a large number of discussions on the net, some quite heated. Today it came up once again on Hacker News, as a link to Scott Stanchfield’s Java is Pass-by-Value, Dammit!.

The answer is absolutely clear, as Scott correctly points out. Java passes the object references by value. This is not the same thing as passing the references directly, and it’s not the same thing as passing the objects as data, i.e., as deep copies. The code sample below shows why the distinction is important.

I only write this to make one more small contribution to the enlightenment of Java programmers, and to highlight a piece of code from the comments of the HN discussion because it’s probably the simplest way of clearly demonstrating the truth of Scott’s article.


public class Test
{
    public static void main(String[] args)
    {
        Object x = null;
        makeString (x);
        System.out.println (x);
    }

    static void makeString (Object y)
    {
        y = "This is a string";
    }
}

If you execute this, you see that the reference to x cannot have been passed to makeObject.

Advertisements

Tags: , ,


%d bloggers like this: