• 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

What is the main Use Static block ?

 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
________________
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic