File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes 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 "static block" Watch "static block" New topic
Author

static block

kedar parundekar
Ranch Hand

Joined: May 10, 2006
Posts: 40
In actual project where we can use static block?
Sidd Kulk
Ranch Hand

Joined: Feb 20, 2007
Posts: 152
Static initializers can be used to instantiate variables. As you would know, the static block is called when the class is loaded, which occurs before object creation.
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968
    
    1

The static block addresses the issue of "when should we initialize a static variable?" Doing it in a constructor is a waste, but where else would you do it, assuming you want a static variable to have a default?

Well, you can do it in a static block.

-Cameron McKenzie
kedar parundekar
Ranch Hand

Joined: May 10, 2006
Posts: 40
1> class Demo1{
static int i=10;// initialize variable i
--------
-------

}
............................................................

2>class Demo2{
static int i;
static {i=10;}// initialize variable i in static initializer block


}

Q. is there any difference between class Demo1 & class Demo2?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Not enough difference to worry about. That initialization is not complex enough to warrant a static block.

Do you see any alternatives to this static block?

There's no HashMap({{"NE", "Nebraska"}, {"PA", ...}}) syntax to do that with the declaration of the map. Some people wish Java had that syntax.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static block