Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1425 :

Posted: Fri Dec 14, 2018 7:05 pm
by OCAJO1
If the following change is made,

Test p1 = new Test();
p1.foo()
Test p2 = p1;
p2.foo();

the print result changes from 10 10 to 5 5. p2.foo() call behavior has changed.

I'm blanking out as to why!

Re: About Question enthuware.ocajp.i.v8.2.1425 :

Posted: Fri Dec 14, 2018 9:02 pm
by admin
Well, you just need to follow the code line by line. If you use the same instance of Test, the while loop will never execute in the second call to foo.
Put a couple of print statements and run the code so see the value of variables.

Re: About Question enthuware.ocajp.i.v8.2.1425 :

Posted: Sun Dec 16, 2018 4:17 pm
by OCAJO1
I think it was momentry inasanity not blanking out. After the first call, b = 0 and without staring a new instance it stays 0 :!:

Re: About Question enthuware.ocajp.i.v8.2.1425 :

Posted: Wed Nov 22, 2023 2:18 am
by iulian
Hi,
I still don't understand the result. I've read the explanation :..."when you call p1.foo() and then p2.foo(), the same field a is incremented 5 times twice and so it will print 10 10."
ok, after the while loop a=5; when you call for example p1.a, does this mean that the while loop runs one more time and that's why a=10?
If not, what is actually happening?
Thank you,
Iulian

Re: About Question enthuware.ocajp.i.v8.2.1425 :

Posted: Wed Nov 22, 2023 7:04 am
by admin
No, look at the while condition. It uses b>0. b is not a static field. It is an instance field, which means there is one b in each instance of class Test. So, when you invoke p1.foo(), p1's b goes from 5 to 0 and when you invoke p2.foo(), p2's b goes from 5 to 0. But both times, the loop increment the same a because a is static. All instances of Test share the same field a. So, it's value is 5 after p1.foo(), and then 10 after p2.foo().