Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^102) | Arithmetic Expressions
Value 1 Value 2
output
System.out
output = System.out;
output.print("Value 1");
System.out.println("Value 2");
Figure 3.3 An object may be changed through any of its references
For example, you could declare a variable of the class PrintStream(which is the class
that defines System.out), called output, and assign System.outto it:
PrintStream output;
output = System.out;
Both variables refer to the same object representing the standard I/O window on the
screen. Printing with either one of them causes the output to appear in the same window,
as shown in Figure 3.3.
Having variables that are synonyms for the same object can occasionally be useful, but
often it leads to mystifying behavior. When the value in an object can be changed through
different variables, it becomes more difficult to keep track of the source of the changes. You
may spend a long time trying to figure out how an assignment statement could possibly
have produced the erroneous value in an object, only to discover that an entirely different
assignment to a synonym for the object caused the problem. At this stage in your program-
ming career, it is best to avoid the use of synonyms.
You should understand that assigning a new object to a variable doesn’t change the ob-
ject that was previously assigned to it. Instead, the variable now refers to the new object; the

Free download pdf