Java Pass By Reference

A colleague of mine, sent me this link in regards to a discussion we were having about passing values and references in Java. It is a good article and includes a couple of descriptions of how Java works, but I still found it rather confusing.

Through my years of coding Java, I’ve learned that this discussion comes up at least once a year with somebody I’m talking to. So, to keep these questions to a minimum and to find a way to explain it that covers probably 90% if not all of the situations simply and easily, I’ll tell you how I always remember it.

My simple rule of thumb is this: If there is a “=” operator assignment inside a method, realize that the change is not going to be visible outside of the method. If the change is made via a set method, such as myDTO.setValue(”changed value”), it will be visible outside the method. The reason is that when you use an “=” operator you are creating a new reference and changing that variable to point to it. The original variable will still be pointing to the old reference, thus not visible outside the method. When you use a setter, you are changing the value that the reference is pointing to, thus it is visible outside of the method.

So that’s my rule of thumb. I haven’t spend much time analyzing it to see if it covers all cases, but I can tell you that it works for me.

Share/Save/Bookmark

Related posts:

  1. Accessing Twitter with Java using HttpClient Today I am going to post about making authenticated REST...
  2. Generate an Java-based Ajax-enabled Web App in 5 Minutes Over the last couple of years there has been a...
  3. Welcome to Java Hair Please stay tuned for meaningful information and great amounts of...

Leave a reply

You must be logged in to post a comment.