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?

1
  • 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. Commented Jun 23, 2015 at 8:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Does JVM guarantee that the static block will be executed only once per application domain ?
The static block gets called each time the class is loaded. If there are multiple classloaders that load the class, the code gets executed multiple times.
if the program starts multiple times, the static block gets called multiple times also
Is it a possibility that the class never gets loaded and hence the method never gets called?
4

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

2 Comments

Would this code be inaccessible from external classes?
Here is the official explanation from Oracle docs.oracle.com/javase/tutorial/java/javaOO/initial.html
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.