Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the main Use Static block ?

 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Mintoo kumar
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

______________
Mintoo
SCJP 1.4
________________
 
Jonathan Wolter
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic