Thursday, August 12, 2010

Java: Pass by Reference or Value?

Java (programming language)Image via Wikipedia
This article explains in clear detail why I've been feeling a trifle bit confused when writing certain Java methods.  Sometimes changes made to an object within a method are retained (or maintained) in the calling method as if Java passes by reference, but sometimes the changes are lost as if Java passes by value.  I've had this question before, and thought that I understood that Java passes by reference.

However, the situation is not as straightforward as that, and this article explains why!  Java does pass by reference, but the reference inside a method is a copy of the reference in the calling method.  Thus changes to the object referenced by the reference will "stick," but try to swap the objects inside a method and nothing is retained outside of the method!  It's because only the references are swapped, but the references are only copies of the original references; thus the original references are unchanged.

No comments:

Post a Comment

Please avoid the use of profanity and be as helpful as you can!