This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "use of static block and constructor " Watch "use of static block and constructor " New topic

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 ?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

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

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:
subject: use of static block and constructor
It's not a secret anymore!