• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Duplicate variables and initialization blocks

 
matt love
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 250
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Astha.

Sounds good to me.

Matt

 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic