You might think that since JAVA is pure object-oriented programming language then it would have been using pass by reference for its parameter passing. However there is a slight difference in JAVA in this idea. To be certain let's clearly state that, JAVA uses Pass by Value for parameter passing. There is no doubt about it. But, the copy of parameter is not the value of parameter itself, instead, copy its reference. Things get weird at this point.
Let me give an example with the garbage collection system. We know that the space for a variable in memory is released when there is no reference pointed to that object anymore. At this step, garbage collection automatically free up that memory space for you.
public static void main(String[] args){
MyObject o = new MyObject();
doSomething(o);
}
public static void doSomething(MyObject o){
o = null;
}
First of all above code will not cause MyObject o be destroyed by garbage collection.
Well if JAVA used Pass by Reference, MyObject o's memory space would be released and there would be no way around in the main method to use that created object after doSomething() method. However, it's not the case. Since JAVA copies the reference when you invoke doSomething() method, JVM will create a new reference variable. So there will be 2 references pointing the o object in the memory. If we give "null" value to one of them, the other will still hold the location information of that object. Which, in turn, concludes that JAVA is Pass by Value. But do not let the name deceives you, yes it includes "Value" but always remember that address of a memory segment is also a value in programming languages. Furthermore there is nothing in JAVA to support Pass by Reference.
Since the article name indicates a comparison we will also talk about C#. C# is almost the same as JAVA with an important difference in parameter passing. There are 2 keywords in C# which are
out and ref and they are used to specify parameters in method invocation. If you use those keywords you will be able to use Pass by Reference idiom. I'm not going to give details but one of them requires initialization of parameter before passing to a method, that's the only difference. I think people really should read the documentation, documentation is really helpful in this manner. With the combination of classic programming language idioms and the documentation everything is crystal clear about this Parameter Passing issue.
No comments:
Post a Comment