Tuesday, February 23, 2010

Pass by what? A water cooler explanation

Verne: Did you read "Pass by what?"
Jules: Yeah, but when I ran the code it don't worked.
Verne: Really, what happened?
Jules: It printed "passed by value", which can't be right. The variable boo is passed by reference, right?
Verne:Well...

Jules: Just start at the beginning?
Verne: Ok, when the member variable boo is first declared the compiler is told to use the name boo to refer to a type of String. Then inside the main() method the String "value" is instantiated and assigned to the variable boo...

Jules: Wait, what does that mean?
Verne: Well, whenever you instantiate an object, behind the scenes a chunk of memory gets allocated on the heap and then a pointer to that memory location is returned.

Jules: What was assigned to what?
Verne: When you assign a reference type to a variable, your variable is actually a pointer to the object. This indirection is transparent in languages like Java and C#.

Jules: What happened next?
Verne: Then boo was passed as an argument to the method changeTheValueOf().

Jules: What does that method do?
Verne: The internals of changeTheValueOf() are very similar to the main() method. Again we are instantiating a String, but this time with the value of "reference" and assigning its pointer to the parameter value.

Jules: Then why did the program print "passed by value" and not "passed by reference"?
Verne: When an argument is "passed by value" a copy of that value is created and passed. Any changes made to the new copy will not be visible in its origin.

Jules: I thought objects were passed by reference?
Verne: Passing a reference type does not mean passing a copy of the value on the heap. To the contrary, a copy of the pointer is created and passed to the method, much like a value type. Since the pointer and the copy of the pointer both point to the same location on the heap, a change made by one is reflected in the other.

Jules: Why was boo not changed?
Verne: The copy of boo's pointer that was passed into the method changeTheValueOf() was assigned to the parameter value. So when changeTheValueOf() reassigned value's pointer to "reference", boo's pointer remained untouched.

Jules: Maybe a more accurate title would have been, "Passing by a copy of a pointer's point"
Verne: Not nearly as catchy.

No comments:

Post a Comment