• Post Reply Bookmark Topic Watch Topic
  • New Topic

which one get initialised first Static variable or static block  RSS feed

 
ganesh pol
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends
can any one tell me
which one get initialised first Static variable or static block

class A1
{
static c1;

Static {

<<<<<<<------- variables initialisation
}
}

and
i think we use Static block only to initialise static variables and not to instance variables is it correct statement?
 
Hentay Duke
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See for yourself. Put some sysouts in both of them and see which one prints to the console first.
 
Philip Heller
author
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like static methods, static initializer blocks may only access static data and methods of the class. Yes, static initializer blocks are used to initialize static data that can't be initialized in a single statement.

As for order of execution, I strongly support Hentay's suggestion. Try the experiment and see what you learn. In a case like this, asking us for the answer is like studying a map. Actually discovering the answer is like hiking around in the territory. I wouldn't want to deprive you of a good hike!
 
Anupam Bhatt
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Philip Heller:
Like static methods, static initializer blocks may only access static data and methods of the class. Yes, static initializer blocks are used to initialize static data that can't be initialized in a single statement.

As for order of execution, I strongly support Hentay's suggestion. Try the experiment and see what you learn. In a case like this, asking us for the answer is like studying a map. Actually discovering the answer is like hiking around in the territory. I wouldn't want to deprive you of a good hike!


That's a perfect inspiration to experiment with thingz... Claps for you !
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!