• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Static block and method.

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic