• Post Reply Bookmark Topic Watch Topic
  • New Topic

static block with forward refrences.  RSS feed

 
Ritesh raushan
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this question also discuss in javaranch but didn't clearify

how is giving output first code-6,7 and second code-66,77












 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ritesh raushan wrote:this question also discuss in javaranch but didn't clearify . . .
That can’t be true. No, no, no, no, no.

This is JavaRanch.

Instance members do not have an order, but static blocks do. Joshua Bloch says, in Effective Java, says that multiple static blocks (well, actually initialisers) are a potent source of confusion. Because they have an order, the field x is initialised to 66 and later to 6, in the first example. Executed in the order the code was declared in.
In the second example, it is the other way round.
You can read about static initialisers in the Java Language Specification; I haven’t read that section for a long time. I think I quoted the right bit. I do not know whether multiple instance initialisers are also executed in the order they are declared.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Language Specification links I posted earlier might not be as helpful as I thought they would.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this JLS section, but it is difficult to read.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!