Confused, whether java uses call by value or call by reference when an object reference is passed?

user617597 picture user617597 · May 25, 2012 · Viewed 53.8k times · Source
public class program1{

    public static void main(String args[]){

        java.util.Vector vc=new java.util.Vector();

        vc.add("111");
        vc.add("222");

        functioncall(vc);

        vc.add("333");

        System.out.println(vc);

    }

    public static void functioncall(java.util.Vector vc){     

        vc=null;    

    }
}

The output of above program is [111,222,333]. but, when I run the following program the output is [333]. Confused when we pass an reference , how it works whether it is call by value or call by reference? and why

public class program1{

    public static void main(String args[]){

        java.util.Vector vc=new java.util.Vector();

        vc.add("111");
        vc.add("222");

        functioncall(vc);

        vc.add("333");

        System.out.println(vc);

    }

    public static void functioncall(java.util.Vector vc){

        vc.removeAllElements();  

    }
}

Answer

Tharwen picture Tharwen · May 25, 2012

It passes the value of the reference.

To shamelessly steal an analogy I saw posted on here a while ago, imagine that each identifier you use is a piece of paper with an address written on it. The address points to a house.

You can change the house (for example, by adding objects to the vector or clearing it), but you're still holding the same piece of paper, and the address still takes you to the same house.

If you set the vector to null, all you're doing is rubbing out the address.

This article explains it in much more detail.