What is static initializer?

Technology CommunityCategory: JavaWhat is static initializer?
VietMX Staff asked 3 years ago
Problem

The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called. If you had to perform a complicated calculation to determine the value of x — or if its value comes from a database — a static initializer could be very useful.

Consider:

class StaticInit {
    public static int x;
    static {
        x = 32;
    }
    // other class members such as constructors and
    // methods go here...
}