This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

preface

Java developers, when they are beginners, are inevitably taught the concept of static initialization blocks. So, what is a statically initialized block? We’ve got a problem or a problem that we’re going to use to describe what a statically initialized block is.

Problem of repetition

In fact, encounter this problem, it is estimated that beginners must encounter the problem.

For most beginners, static initialization blocks are used to set values for static members.

However, most people don’t understand why this static initializer block is used at all.

For example, we declare a static member that has no assigned value. And then I write a couple of lines of static initialization blocks to do variable assignment, value assignment.

So, we are wondering why static{… } this kind of code.

Also, we largely don’t understand that static{… } and {… The difference between}

Problem solving

First, let’s talk about how non-static initializers work.

{
    // Do Something...
}
Copy the code

A static initializer block is executed only once, and a non-static initializer block is created every time an object is created.

Such as:

public class Test {

    static{
        System.out.println("Static");
    }

    {
        System.out.println("Non-static block");
    }

    public static void main(String[] args) {
        Test t = new Test();
        Test t2 = newTest(); }}Copy the code

Method executes with the following output

Static
Non-static block
Non-static block
Copy the code

It looks something like this, and we can see the difference

So, why write this.

Many reasons, I wrote this because of this characteristic. Such as

static {
    try {
        Class.forName("com.example.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new ExceptionInInitializerError("Cannot load JDBC driver.", e); }}Copy the code

The connection of the database, must be solved once, the other is not needed

conclusion

We are very familiar with this Java concept. Then, we should be more familiar with the way we learn. Combined with more examples, I believe there will be very good help