5

Possible Duplicate:
Static Block in Java

I came across the following use of static and did not figure out what it does. I am aware of using for example static String hello = "World"; but I do not understand the following.

static {
   loadFromProperties(new Properties());
}
Community
  • 1
  • 1
dokaspar
  • 8,186
  • 14
  • 70
  • 98
  • The static block in the program is the first to execute when a VM is initialized. More specifically, the static block is used for initializing the static constants. public static final int MAX_ITER; static { int dummyMaxIter = AClass.calculateABC(); if (dummyMaxIter >= 0) { MAX_ITER = dummyMaxIter; } else { MAX_ITER = 0; } } See the above segment. can initialize the `MAX_ITER` directly from `AClass.calculateABC()`. But you need to validate the value returned by `AClass.calculateABC()` before assigning. – Mohan Jul 17 '12 at 12:27
  • you are right, this is a duplicate. sorry about that. – dokaspar Jul 17 '12 at 12:31

2 Answers2

8

It's called a static initializer. It's a block of code that runs when the class is initialized.

Related question (probably a dup actually):

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
3

This is called static blocks. Those are executed when class is loaded/initialized but before instantiation. You can use then to initialize static members/fields.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
  • Actually it's executed when the class is *initialized*. (In practice you seldom notice the difference though.) – aioobe Jul 17 '12 at 12:14