# HeadFirst Java, Ch3 Pool Puzzle

Yong Lee
Greenhorn
Posts: 6
So I'm a little stumped...the following code produces this output:

triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = 28.0
y = 4, t5 area = 343

What has me stumped is the last line of output...I understand that both t5 and ta[2] are pointing to the same Triangle object, and that by setting ta[2].area = 343, t5.area will also = 343. But where does "y = 4" come from - if y = x, and x is set as 27, where is the value changed to 4? Any help would be appreciated, thanks!
[ May 26, 2008: Message edited by: Campbell Ritchie ]

chandra mohan
Greenhorn
Posts: 20
It is straight forward.

After the while loop you are setting y = x where the value of x is 4 at that time. Later you changed the value of x to 27 but not �Y� so it printed value of y as 4.

Yong Lee
Greenhorn
Posts: 6
First, thanks for the fast reply!

Second, duh - I hadn't thought about the value of x as the loop was exited...for some reason, I thought that since x was given a new value, y took the same value. I see now that since the line "y = x" was written before "x = 27", y retains the previous value of x. Thanks!

Campbell Ritchie
Sheriff
Posts: 50644
83

Yong Lee
Greenhorn
Posts: 6
Sure, will use code tags in the future. Thanks for the heads up.

Campbell Ritchie
Sheriff
Posts: 50644
83
Originally posted by Yong Lee:
Sure, will use code tags in the future. Thanks for the heads up.
Thank you. You see how much better it looks with the code tags added. There are buttons below the "message" box for formatting your posts.

Albert Park
Greenhorn
Posts: 28

But i am also having a trouble understanding the last part.

On line 17 and 18, y was 4, then the value changed to 27. but it had no influence on printing out y as 4(line21).
On line 19 and 20, t5=ta[2]. i am thinking t5=18 from previous area ta[2]. Then why all of sudden from line 20, t5.area changed to 343? should it not have any influence on t5 value, and print out 18 as area(line22) instead of 343?

Thanks.

Bill Clar
Ranch Hand
Posts: 163

As to your second question, ta[2] references a Triangle object. When you call

is a new object created, or does t5 reference the same object as ta[2]?

Nick de Waal
Ranch Hand
Posts: 42
Yong Lee wrote:So I'm a little stumped...the following code produces this output:

triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = 28.0
y = 4, t5 area = 343

What has me stumped is the last line of output...I understand that both t5 and ta[2] are pointing to the same Triangle object, and that by setting ta[2].area = 343, t5.area will also = 343. But where does "y = 4" come from - if y = x, and x is set as 27, where is the value changed to 4? Any help would be appreciated, thanks!
[ May 26, 2008: Message edited by: Campbell Ritchie ]

I realize this is an old post but I run the exact same code as above (chapter 3 HeadFirstJava),
and I receive the following :