23

Recently in a lot of programs I've been looking at, I've noticed

static {
    //some code here
}

I'm just looking for some information about this particularly, I'm used to blocks of code all being in methods, or simply classes, does this simply set all code within the block with a static modifier, or is there something more to it?

Dan
  • 649
  • 4
  • 11
  • 19
  • I guess you can consider it to be like a constructor, but for the class, not any instances of the class. Although I assume you can have multiple static blocks, but of course only one constructor per class. – Alexander Mills Jun 23 '15 at 08:34

3 Answers3

15

This might be a duplicate question from Static Initialization Blocks

The static block only gets called once, no matter how many objects of that type you create.

Community
  • 1
  • 1
Ahmad
  • 12,336
  • 6
  • 48
  • 88
4

The code inside a static block is executed first (e.g. before your constructor) once the JVM loads your class.

Juvanis
  • 25,802
  • 5
  • 69
  • 87
1

Static blocks get called once (at a class level) and does not belong to a specific instance.

you can find more info (with good examples) here, or in the official oracle documentation.

Ofir Farchy
  • 7,657
  • 7
  • 38
  • 58