Aliasing

Aliasing means that more than one reference is tied to the same object, as in the preceding example. The problem with aliasing occurs when someone writes to that object. If the owners of the other references arent expecting that object to change, theyll be surprised. This can be demonstrated with a simple example:

a new Alias1 reference is created, but instead of being assigned to a fresh object created with new, its assigned to an existing reference. So the contents of reference x, which is the address of the object x is pointing to, is assigned to y, and thus both x and y are attached to the same object. So when xs i is incremented in the statement:

x.i++;

ys i will be affected as well. This can be seen in the output:

x: 7
y: 7
Incrementing x
x: 8
y: 8

One good solution in this case is simply not to do it; dont consciously alias more than one reference to an object at the same scope. Your code will be much easier to understand and debug. However, when youre passing a reference in as an argumentwhich is the way Java is supposed to workyou automatically alias, because the local reference thats created can modify the outside object (the object that was created outside the scope of the method). Heres an example:

The method is changing its argument, the outside object. When this kind of situation arises, you must decide whether it makes sense, whether the user expects it, and whether its going to cause problems.

In general, you call a method in order to produce a return value and/or a change of state in the object that the method is called for. Its much less common to call a method in order to manipulate its arguments; this is referred to as calling a method for its side effects. Thus, when you create a method that modifies its arguments, the user must be clearly instructed and warned about the use of that method and its potential surprises. Because of the confusion and pitfalls, its much better to avoid changing the argument.

If you need to modify an argument during a method call and you dont intend to modify the outside argument, then you should protect that argument by making a copy inside your method. Thats the subject of much of this appendix.