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?
Yes. It is possible to define multiple static blocks in a java class.
In Java, when we declare a field static, exactly a single copy of that field is created and shared among all instances of that class. It doesn't matter how many times we instantiate a class. There will always be only one copy of static field belonging to it.
There can be multiple static initialization blocks in a class that is called in the order they appear in the program.
Static blocks can be used to initialize static variables or to call a static method. However, an instance block is executed every time an instance of the class is created, and it can be used to initialize the instance data members.
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.
The code inside a static block is executed first (e.g. before your constructor) once the JVM loads your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With