What is and how does a static block work in Java? [duplicate]

2

Studying Java I came across the following code:

static {
    System.out.println("bloco estático inicializado");
}

Then I ended up calling the main method and the block was executed. How does this happen? I know that a static method does not need the instance of an object to refer to it, but we need to at least call them by name. I do not quite understand why the block runs.

    
asked by anonymous 26.09.2016 / 20:30

2 answers

1

A static block runs only once, immediately after the first reference to class , that is, in memory loading.

As the static block runs on the load of the class, it will be executed before the call to the class constructor. Within a static code block we can access only static attributes and methods.

Example

static {
  XABLAU = 0;   // Bloco executado uma única vez quando a classe é carregada
}

Details

26.09.2016 / 20:50
1

Initialization blocks run when an instance is created or when the class is loaded by the JVM. They have no return, name, and parameters.

Static initialization blocks run only when the class is first loaded. Instance boot blocks run whenever a new instance is created.

Rules, removed on the site Java Naveia :

  
  • Instance initialization blocks are executed in the order they appear;
  •   
  • Static initialization blocks only run once, when the class is first loaded into the JVM;
  •   
  • Instance initialization blocks run every time a new instance is created and after calling the super() method inside the   constructor.
  •   

If there are multiple classes in the multi-block inheritance tree   static, they will all run before the instance blocks.

Reference: Java nave

    
26.09.2016 / 20:42