Hi,
I have trouble understanding the answer to question 3.3 from Programmer's Guide to Java Certification, A Comprehensive Primer, Second Edition. Here's the question:
What will be the result of attempting to compile and run the following program?
Select the one correct answer.
a. The program will fail to compile.
b. The program will print mouse when run.
c. The program will print cat when run.
d. The program will print dog when run.
e. The program will randomly print either cat or dog when run.
The answer is c. The book provides the following explanation:
Strings are objects. The variables a, b, and c are references that can denote such objects. Assigning to a reference only changes the reference value. It does not create a copy of the source object or change the object denoted by the old reference value in the destination reference. In other words, assignment to references only affects which object the destination reference denotes. The reference value of the "cat" object is first assigned to variable a, then to variable b, and later to variable c. The program prints the string denoted by the variable c, which is "cat".
My interpretation of the explanation is that references are passed, not values. I interpreted the code as follows:
----------------------------------
I was about to submit the post when I thought of a possible explanation. I now think in terms of object references rather than the values of the strings:
"mouse" = Object1
"cat" = Object2
"dog" = Object3
The equals sign on the comments now denotes a reference to.
Since Object2 = "cat" that explains the answer.
Does this make sense?
Thanks
P.S.: I was trying to modify and run the source code and print out the Object reference (or whatever it's called, i.e.: java.lang.Object@cac268). But I have tried
System.out.println((Object)c.toString());
but it doesn't work. I am looking at java.lang.ref.Reference. Am I on the right track? Thanks