| Author |
Duplicate variables and initialization blocks
|
matt love
Ranch Hand
Joined: Jan 25, 2010
Posts: 62
|
|
prints in the following order:
aaa
bbb
ccc
bbb
To someone who doesn't know what's going on, this looks pretty strange.
First question: why does it appear the compiler allows a to be declared a second time by String a = "ccc" in the initializer block?
I venture to guess the answer to that question might resolve the second question:
why is it the value bbb that remains for the variable a as illustrated in the println from main()?
Intuitively for me, a should equal ccc in the main() method.
Many thanks.
Matt
|
 |
Astha Sharma
Ranch Hand
Joined: Oct 15, 2011
Posts: 128
|
|
|
Im not sure, but i guess its because instance variable 'a' when declared first time, on object creation it get stored with object in heap. Inside the initialization block 'a' start referring new string 'bbb'. When declaration of 'a' appear for the second time, it gets stored in stack because it is being declared in initialization block. When initialization block ends, reference variable 'a' gets destroyed and string 'ccc' goes to string pool with no reference. The reference variable 'a' stored with object is still referring 'bbb'. So bbb gets printed in main. I think this is the reason.
|
 |
matt love
Ranch Hand
Joined: Jan 25, 2010
Posts: 62
|
|
Thanks Astha.
Sounds good to me.
Matt
|
 |
Dan Drillich
Ranch Hand
Joined: Jul 09, 2001
Posts: 1061
|
|
matt love wrote:
First question: why does it appear the compiler allows a to be declared a second time by String a = "ccc" in the initializer block?
The variable is within a block so it's a new variable.
Interestingly, Initializing Instance Members says -
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
Regards,
Dan
|
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
|
 |
James Boswell
Ranch Hand
Joined: Nov 09, 2011
Posts: 344
|
|
The line
is a new local variable a and in no way refers to the instance member with the same name. This also explains why the instance member has the value "bbb" when the final line of the main method is executed.
|
 |
 |
|
|
subject: Duplicate variables and initialization blocks
|
|
|