wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A Difficult question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A Difficult question " Watch "A Difficult question " New topic

A Difficult question

Sricharan Modali

Joined: Mar 30, 2004
Posts: 19
For the question What is the result of compiling and running this...

I Thought the answer wud be
but the answer is
Can anyone please tell me why counter is not incremented and made 2 after the calls it is incremented at
A a1 = new A();
void m1() {new A().new B();}
Edited by Corey McGlone: Added CODE Tags
[ April 01, 2004: Message edited by: Corey McGlone ]
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Let's try to go step by step.
First, we have this, which executes the constructor for A:

Then, we execute this line, which causes use to create a new A object and a new B object:

Next, we execute this line of code, which uses the original A object that we created, which has the name A0, and creates a new B object.

Finally, we execute what really boils down to the same line as the last one. We create a new B object, but we use the original A object.

That gives the total output of A1B0A0B1A0B2.
I hope that helps,

SCJP Tipline, etc.
Sricharan Modali

Joined: Mar 30, 2004
Posts: 19
oh Sorry Corey
I thought there was a Static modifier before variable name too. I just thought
cos all other variables are defined static. I overlooked it. Please remove this post from the forum as it can mislead others.
I agree. Here's the link: http://aspose.com/file-tools
subject: A Difficult question
It's not a secret anymore!