What is and how does a Static block work in Java?

Asked

Viewed 2,225 times

2

Studying Java I came across the following code:

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

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

2 answers

1

The boot blocks are executed when an instance is created or when the class is loaded by the JVM. They have no return, name and parameters.

The static boot blocks are executed only when the class is first loaded. Instance initialization blocks run whenever a new instance is created.

Rules, withdrawals on the website Java Naveia:

  • instance initialization blocks are executed in the order they appear;
  • static startup 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 the method call super() within the builder.

If there are multiple classes in the inheritance tree with multiple blocks static, all of them will be executed before the instance blocks.

Reference: Java naveia

  • The reference link is broken.

  • @diegofm, tidy up.

1

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

Like the static block is executed on class loading, hence 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.