Your question demonstrates a common error made by Java language newcomers. Indeed, even seasoned veterans find it difficult to keep the terms straight.
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
badSwap() method for example:
badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from
since Java passes object references by value as well. Now, here is where it gets tricky:
If we execute this
main() method, we see the following output:
The method successfully alters the value of
pnt1, even though it is passed by value; however, a swap of
This is the major source of confusion. In the
nothing more than object references. When you pass
pnt2 to the
Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an
object to a method.
Figure 1. After being passed to a method, an object will have at least two references
Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.
Figure 2. Only the method references are swapped, not the original ones