Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use of static block and constructor

 
Ayan Dutta
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nav Letha
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic