Saturday 26 May 2018

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




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



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...