aspose file tools
The moose likes OO, Patterns, UML and Refactoring and the fly likes If Java were pass by reference... Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Reply Bookmark "If Java were pass by reference..." Watch "If Java were pass by reference..." New topic
Author

If Java were pass by reference...

marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

I "know" that Java always passes by value, but I want to verify my understanding of what this means. Consider the following code snippet.

In the above code, an instance of A is created and a reference to that instance is assigned to the variable a1. Then a copy of that reference (that is, a value) is passed to the method changer, where it's assigned to a local variable a2. Now, a2 is pointing to the same object as a1, so the actual object can be modified from within the method.

But here's the distinction: When a2 is assigned to null, this has no effect on a1 because the reference originally assigned to a2 was only a copy (a value). On the other hand, if Java were actually pass by reference, then instead of a copy of the reference, a2 would have held the reference itself, and changing it to null would have also changed a1 to a null reference.

Is this accurate?


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
Originally posted by marc weber:
Is this accurate?


Yes.


Mani
Quaerendo Invenietis
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: If Java were pass by reference...
 
Similar Threads
garbage collection question k&b practice exam 3
Doubt in Garbage Collection
Garbage Collection Problem
Question about object creation
Problem with GC exercises