wood burning stoves 2.0
The moose likes Java in General and the fly likes When will we go for static block...? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "When will we go for static block...?" Watch "When will we go for static block...?" New topic

When will we go for static block...?

Naveen Raja

Joined: Jul 28, 2006
Posts: 10

I know that static block can be defined in a class,but when we have to go for it and how compiler treats it..?

Thanks in Advance

Nikhil Goel
Ranch Hand

Joined: Jul 11, 2003
Posts: 32
static blocks are intialized the first thing even way before constructors.

Usage can be to intialize connection pools etc . Normall all other utility stuff can be taken care in static blocks
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
JDBC driver, for example, use static blocks to register themselves to the DriverManager. That's why loading a JDBC driver by Class.forName initializes it.

Another use is to initialize complex static variables, such as Collections etc.

They shouldn't be used too often, though - most often there are better (more flexible) alternatives to static blocks.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Sol Mayer-Orn
Ranch Hand

Joined: Nov 13, 2002
Posts: 311
Just wanted to add that a static block is executed when the class is first loaded & initialized for use.
The JVM spec has more accurate definitions about this, but usually you'll notice that a class is loaded & initialized when you first use it - e.g. when you first try to create an instance, or use some static methods/variables.

A classic example:
Pratibha Malhotra
Ranch Hand

Joined: Dec 21, 2003
Posts: 199
To add to Naveen Question, what all resolutions happen at compile time and what all are left for run time.

can someone pls point me to appropriate resource

thanks ahead,

~ Pratibha Malhotra<br /> <br />Sun Certified Java Programmer<br />SCEA 1.4 (In Progress)<br />~~~~~~~~~~~~~~~~~~~~~~~~~~~<br />"Many of life's failures are people who did not realize how close they were to success when they gave up!!"
I agree. Here's the link: http://aspose.com/file-tools
subject: When will we go for static block...?
It's not a secret anymore!