• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static block and method.  RSS feed

 
Deena Raj
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If i have a static block and static method in my program, which gets executed first? Also why is the main method Static?
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More of a beginners' question . . .

The main method is static because the JVM needs access to it before any objects can be created.

As for whether a static method or static block is executed first, write a class with a static method and a static block including "System.out.println("Static block");" or similar and see what happens.
 
Dinesh Arora
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
When a class is loaded, static blocks get executed first. static methods don't get executed.
Consider a case where you have static variable and staic blocks as well, what happens when a class is laoded-
static variables - gets initialised first.
Next Static blocks get executed, in the sequence they appear.

Ex -

class test{

static { // gets executed second
i = 10;
}
static int i=0; // gets executed first

static {....} // gets executed third


Burn this in your mind, if you are plannig for SCJP, 'coz they would sure trick you on this.

}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!