• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Block and initialization

 
Chandra shekar M
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 440
Eclipse IDE Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
lalit sangar
Greenhorn
Posts: 1
Eclipse IDE Java Java ME
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks All,
 
James X Peterson
Whizlabs Java Support
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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

Regards,
James
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic