There is only 1 object created and reference variables e1 e2 refer to that object only. Whatever changes are made in count is valid for both the reference variables. I guess printing hello 4 times is simple as it the while will be looped 4 times. The value of the count well only 1 object means only 1 count but 2 reference variables.
x = 0 e1.count=e1.count+1; making count = 1
x = 1 e1.count=e1.count+1; making count = 2 then if(x>0) will be executed e2.count=e2.count+e1.count(2+2); making count = 4
x = 2 e1.count=e1.count+1; making count = 5 then if(x>0) will be executed e2.count=e2.count+e1.count; making count = 10
x = 3 e1.count=e1.count+1; making count = 11 if (x==3) e2.count = e2.count+1; count = 12
if (x>0)e2.count=e2.count+e1.count(12 + 12); count = 24
I guess this thing you could have found out by compiling and executing the program and putting the System.out.println(e2.count) in the while loop. Try out the programs
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
Joined: Jul 25, 2009
Thanks. I got the part about the hello method -- I just wasn't sure how e1 and e2 related to each other -- I thought that the value of e2 just depended on e1, but I didn't know that the value of e1 was affected as well. The exercise was optional -- it was a puzzle kind of thing, and I tried to figure it out, but couldn't. The answer wasn't just the problem; I could compile and run the program, but like I said, even though I compiled and ran it, I didn't understand how to get the answer of 24 because I didn't know how the two objects' values related to one another.
I do not have the book handy, but I believe the relationship between e1 and e2 is the point of the puzzle. The question you want to ask yourself is "How many unique objects do you have?" and also how would the output be changed if you changed one line of code to this:
Joined: Jul 25, 2009
with the change to the code, the number would be 10 -- which I understood. But like I said, I just didn't get this one. There wasn't anything in the example to explain it. It was a bonus question, but in the chapter nothing was explained about this.
Joined: May 16, 2008
In that excerise e1 and e2 are the same object with two names. It would be the same as Laurence = Larry, same person, two names. However Chris = new Person(), would be a new object. The HFJ will talk about passing by reference, understanding the difference between a reference to an object, and the actual object may be confusing at first but it will be important to understanding how the program works.
subject: Would like help about this excercise in HFJ