I
I
iscateli2021-12-25 15:43:21
Java
iscateli, 2021-12-25 15:43:21

What are curly braces in Java?

I came across such a design in the classroom, I don’t even know how to search for it in Google.

static {
         System.out.println("Инициализация Initable2");
       }


Full class example:

class Initable2 {
       static int staticNonFinal = 147;
       static {
         System.out.println("Инициализация Initable2");
       }
    }


What is it used for when such a design is needed?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vamp, 2021-12-26
@iscateli

This construct is called a static initialization block . There is also exactly the same dynamic initialization block , only without the static keyword.
Initialization blocks are needed to set initial values ​​for class fields.

class Initable2 {
    static int staticNonFinal;

    public static void main(String[] args) {
        System.out.println(staticNonFinal);
    }
}

This example will output zero even though no value has been assigned to staticNonFinal. Java guarantees that any class fields will be initialized with a "null" value. That is, the compiler implicitly inserts a static initialization block into the class that sets the staticNonFinal variable to zero.
class Initable2 {
    static int staticNonFinal;

    // Вот этот блок будет добавлен к
    // вашему классу во время компиляции.
    static {
        staticNonFinal = 0;
    }

    public static void main(String[] args) {
        System.out.println(staticNonFinal);
    }
}

Of course, you can initialize variables with your own values:
class Initable2 {
    static int staticNonFinal = 42;

    static String a = "hello";

    static Cache<String, Integer> b = CacheBuilder.newBuilder()
        .maximumSize(100)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build();
}

And then the compiler in the initialization block will substitute your values ​​instead of zeros:
class Initable2 {
    static int staticNonFinal;

    static String a;

    static Cache<String, Integer> b;

    static {
        staticNonFinal = 42;
        a = "hello";
        b = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build();
    }
}

And if your variable needs some kind of complex initialization that cannot be represented in one line (as in the Cache example), then you will have to write the initialization block explicitly manually:
class Initable2 {
    static int staticNonFinal = 42;

    static Map<Integer, String> statusCodes = new HashMap<>();

    static {
        statusCodes.put(200, "OK");
        statusCodes.put(404, "Not Found");
        statusCodes.put(418, "I'm a teapot");
    }
}

And then the compiler will generate the following code for you:
class Initable2 {
    static int staticNonFinal;

    static Map<Integer, String> statusCodes;

    static {
        staticNonFinal = 42;
        statusCodes = new HashMap<>()
        statusCodes.put(200, "OK");
        statusCodes.put(404, "Not Found");
        statusCodes.put(418, "I'm a teapot");
    }
}

Non-static fields are initialized in exactly the same way using a dynamic initialization block (there is no static keyword before such a block and looks like just curly braces in the class body). Every time a class object is created, the dynamic initialization block is executed first, and then the constructor. It's in that order. The static initialization block is executed once when the class is loaded into memory.
Dynamic initialization blocks are rarely used by programmers, since it's easiest to do "initialization" in the constructor (in quotes, because the formal initialization has already been done before the constructor runs and the constructor simply overwrites the already initialized value with its own, so the more accurate term here would be reassignment). But static initialization blocks are used quite often, since static constructors do not exist.
All these initialization blocks were invented by the creators of the java language in order to eliminate a whole class of severe errors associated with access to uninitialized variables, which is typical for the C and C++ languages.

D
Dmtm, 2021-12-25
@Dmtm

well, it’s also written there - a static initialization block, you can display in the log that the class was initialized, you can fill in other static fields, in general, you can create various problems for yourself

D
Dmitry Roo, 2021-12-25
@xez

public class InitDemo {

    static String staticString;
    String s;

    static {
        System.out.println("внутри static");
        staticString = "Инициализация статического поля";
        // s = "Тут нельзя обращаться к не static полям";
    }


    public InitDemo(String s) {
        System.out.println("внутри  конструктора");
        this.s = s; //  А в конструкторе уже можно
    }

    {
        System.out.println("внутри {}");
        s = staticString; // Это будет выполнено ДО конструктора
    }

    public static void main(String[] args) {
        var initDemo = new InitDemo("Строка из конструктора");

        System.out.println(initDemo.s);
    }
}

внутри static
внутри {}
внутри  конструктора
Строка из конструктора

O
Orkhan, 2021-12-25
Hasanly @azerphoenix

Good evening.
Read about non-static and static initialization blocks.
https://vertex-academy.com/tutorials/en/bloki-inic...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question