Meaningless Drivel is fun!
The moose likes Java in General and the fly likes Static Block and initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static Block and initialization" Watch "Static Block and initialization" New topic

Static Block and initialization

Chandra shekar M
Ranch Hand

Joined: Dec 20, 2006
Posts: 155

the above code is getting translated in to

as a result it throws NPE at m.put. But I think It should be like this

because m is used by method load? But why is this not happening. Is it because of the order in which it is defined?
Saif Asif
Ranch Hand

Joined: Aug 11, 2011
Posts: 440

The static block will be called at runtime before any constructor is called and in order to use any static member inside the static block , they have to be initialized before the static class appears.

Muhammad Saif Asif Mirza
lalit sangar

Joined: Feb 21, 2013
Posts: 1

Hi Chandra sehkar,

Yes, it is because of the order of your static code. All static code of a class i.e. all static variables and static blocks at runtime are initialized in the order they appear in code. so in this case declaring Map m before static block will fix NPE.

Chandra shekar M
Ranch Hand

Joined: Dec 20, 2006
Posts: 155
Thanks All,
James X Peterson
Whizlabs Java Support
Ranch Hand

Joined: Feb 26, 2013
Posts: 158

static block is executed before main() method and the static will execute in the order of static blocks.

I agree. Here's the link:
subject: Static Block and initialization
It's not a secret anymore!