Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static code block [duplicate]

Tags:

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?

like image 666
Dan Avatar asked Nov 10 '12 05:11

Dan


People also ask

Can we have multiple static block in Java?

Yes. It is possible to define multiple static blocks in a java class.

Why static is single copy in Java?

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.

How many static initializers can you have?

There can be multiple static initialization blocks in a class that is called in the order they appear in the program.

Can we initialize static variable in static block Java?

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.


2 Answers

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.

like image 164
Ahmad Avatar answered Sep 19 '22 15:09

Ahmad


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

like image 40
Juvanis Avatar answered Sep 20 '22 15:09

Juvanis