• Post Reply Bookmark Topic Watch Topic
  • New Topic

the order of static fields  RSS feed

 
Blake Edward
Ranch Hand
Posts: 106
4
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK,

So suddenly I am unsure of something. In the following class, which is read first; the static field or the main method?

class Test{
static int a = 3;
public static void main(String args []) {
//some code}
}

I put some code in Eclipse and have tried to look at the hierarchy. It would point to all static fields being initialized in order from top to bottom, including the main method.
I had thought that the main method was always the first thing in a public class to be initialized, regardless of where in the code it resides. Am I reading the Eclipse hierarchy
wrong? I find Eclipse very difficult, especially since I typically code in Textmate. I just want to see how my code is operated upon, in the order in which the compiler/jvm
would operate on it. Any help would be appreciated. So many setbacks. I have been studying my butt off then something like this pops up and fills me with doubt and really
deflates me.

Thanks
 
khadar valli
Greenhorn
Posts: 26
Java MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Definitely first it reads static variables and then it will go to methods...
 
Dave Tolls
Ranch Foreman
Posts: 3067
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JLS defines it here.
When the class is loaded (which has to happen before any method or static variable in the class can be accessed) all the static initialisers are called in the order they appear in the class.
So all static variables and any static {} code blocks will all be initialised or run before the main() method is called.
 
Campbell Ritchie
Marshal
Posts: 56576
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In which case, beware of mixing ordinary initialisation and static initialisers. Also beware of multiple initialisers. The order of initialisation can cause unexpected results; there is an example in Bloch and Gafter's book Java Puzzlers, but I cannot remember the full details. I don't have my copy to hand at the moment.
 
Blake Edward
Ranch Hand
Posts: 106
4
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all, and thanks Dave for the link. I will play with some scenarios tonight just so I can get this through my thick head.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!