Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If Java were pass by reference...

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marc weber:
Is this accurate?


Yes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic