File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes What is the main Use Static block  ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is the main Use Static block  ?" Watch "What is the main Use Static block  ?" New topic

What is the main Use Static block ?

Praveen Kumar
Ranch Hand

Joined: Nov 06, 2006
Posts: 133
We can write static blocks in java like

static {



Here we can initailise the varaibles before its construcor runs.

Do we have any another use of the Static block ?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

Actually that code is run when the class is loaded. Even when there will never be any object created, the code will still run. What you are thinking about are initializer blocks, which are the same but without the static keyword.

Now these static initializers should be used to run code that are required for a class to function properly. That could be any code required.

One example is loading libraries:

How To Ask Questions How To Answer Questions
Mintoo kumar
Ranch Hand

Joined: Aug 21, 2007
Posts: 61
Rob , you made a correct point.
As it's name suggest static initalizer block.So there would be some piece of information which would either initialize in or intialized by this block.
if you explore the Java API , you will find in so many API ,which require native code to be loaded first to work class properly,that piece of code can be loaded with the help of static block.Loading of library.

SCJP 1.4
Jonathan Wolter

Joined: Nov 26, 2007
Posts: 12
Also, because the nature of static initialization blocks running when the class is loaded, you can *never* prevent them from running.

This is why it's often something you want to avoid in your own code, especially for expensive work that could happen elsewhere. It makes testing harder.
I agree. Here's the link:
subject: What is the main Use Static block ?
It's not a secret anymore!