File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

Static Block and initialization

Chandra shekar M
Ranch Hand

Joined: Dec 20, 2006
Posts: 135
Strange


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
OCJA(5/6) OCJP(6) OCJWCD(6)
lalit sangar
Greenhorn

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.


Lalit
Chandra shekar M
Ranch Hand

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

Joined: Feb 26, 2013
Posts: 158
Hi,

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

Regards,
James
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Block and initialization