Pass by value and pass by reference can be daunting at times, and I too have been confused and frustrated at all of the babbling about whether or not Java is one or the other, that is, until I saw an article featuring the Litmus test. I've seen the Litmus test in college, but it didn't make sense completely until reading Scott Stanchfield's "Dammit" article.
Java is clearly pass by value. Scott Stanchfield's statement says it best: "Objects are not passed by reference. A correct statement would be Object references are passed by value."
The output is as follows:
The output is:
However, changes to the reference itself are not reflected. A rule of thumb to remember is that when implementing the swap method, you can only change data by calling setter and getter methods, or by accessing public properties. However, making changes to the object reference instruct the object reference to point to a different location. This is why swapValue worked as expected while swap did not.
Below is a sequence of "visual art" to demonstrate the concepts visually:
The value of the object referenced by B is changed to a new value, but the object reference still points to the same location in memory.
For A, the "new" operator created new space in memory and instantiates a new object. The "12" is located in a different spot in memory.
B, on the other hand, has a value that was set using a setter method. Thus, the value has changed from "7" to "2" without destroying the original object.
Objects A, C, and D all point to the same place in memory. If a setter method is called on one of the object references, the value is changed in all 3 object references because they all point to the same location in memory.
A good analogy to use to explain this concept is "nicknames". For instance, my name is James, but people also refer to me by Jim. Additionally, I've been called "Mort" before as well. All three names point to the same object, me! In the example I've shown you, A, C, and D are all names of the same object.