Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static block

 
kedar parundekar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In actual project where we can use static block?
 
Sidd Kulk
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic