wood burning stoves 2.0*
The moose likes Java in General and the fly likes use of static block and constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "use of static block and constructor " Watch "use of static block and constructor " New topic
Author

use of static block and constructor

Ayan Dutta
Ranch Hand

Joined: Oct 16, 2005
Posts: 94
we can provide any initialization inside static block and also inside constructors . can anybody provide a real life example when a static block initialization is a must , not constructor ?
Regards,
Ayan
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

When you want to initialize static data -- data that is shared by a whole class. Code in a constructor will execute every time an object is created, which is generally not what you want for static data.


[Jess in Action][AskingGoodQuestions]
Nav Letha
Greenhorn

Joined: Oct 22, 2006
Posts: 8
Let's say you have a static HashMap and you want to initialize it only once.

static {

s_map.put("first", firstObj);
s_mpa.put("second", secondObj);
...
}

May be others can give more meaningful examples.
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
Static blocks are comparable with method blocks where you can put some code stuff in it, with the difference that they're executed only once per runtime, before the instance initialization blocks and the constructor. The initialization blocks and the constructor are executed everytime when an instance is created.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: use of static block and constructor
 
Similar Threads
Constructor inside the static block
What is the order of Initialization
Initializing Sequence
Blocks
Core Java