Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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();        } } 
like image 480
user617597 Avatar asked May 25 '12 07:05

user617597


1 Answers

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.

like image 69
Tharwen Avatar answered Oct 20 '22 15:10

Tharwen