Here is the most confusing paradigm of the Java even confused by an expert programmer. It is a most common mistake which states that primitives are pass by value and objects are pass by reference. This is not totally true. Actually it is half true. Primitive types like int, double, float are indeed pass by value, hence this part is true. However, objects like Person (which I made up) are pass by value too. Pass by reference concept comes from C++ in which object can be passed to a method and method can modify/change the object as it is the original one. In java you can modify the object, but if you change the reference then you can no longer change it. Here is an famous swap example which illustrates if the language is pass by value or pass by reference. If swap can be achieved then it is pass by reference.
void swap (Point arg1, Point arg2) {
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
so in main you have something like this:
Point p1...;
Point p2...;
swap(p1,p2);
In Java it works as follow: first note that p1 (or p2) is not an object's itself. It is just a reference to a Point object (like in pointer). When we pass p1 and p2 to swap function Java creates Point objects arg1 and arg2 and copy the addresses of p1 and p2 to these arguments. Therefore it is like another reference to actual copy of the object. You can think of we have two references to Page (p1) object in this point. Same argument can be made for p2. Therefore swapping arg1 and arg2 actually just change the arg1 with arg2 and when the swap function finished they will be deallocated. Hence no effect will be visible by either p1 or p2. This actually proves Java uses pass by value not pass by reference. I hope it helps.
I agree! Such a confusing topic in Java - it took a while for it to settle in because of the fact that sometimes passing by value looks like passing by reference, so it's a bit deceiving.
ReplyDeleteAnother good reference here:
http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-reference-or-by-value/