Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is initializers for static fields in Java

I have got the following line from Oracle Java tutorial You can find this here Execution under the heading "12.4. Initialization of Classes and Interfaces"

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

It will be great if someone explain me How "initializers for static fields" is referring to "class variables".

like image 343
Saurav Pandit Avatar asked Feb 09 '23 04:02

Saurav Pandit


1 Answers

A "class variable" is a variable that is declared as a static property of a class. By "initializers for static fields" they are referring to the initialization of these static variables, which happens when the class is loaded. Here's an example:

public class MyClass {
    private static int num = 0; //This is a class variable being initialized when it is declared
}

Another way to initialize static fields is to use static blocks:

public class MyClass {
    private static int num;
    static {
        num = 0; //This a class variable being initialized in a static block
    }
}

These static blocks are run from top to bottom when the class is loaded.

In the end, the quote is trying to say that "class variable" is just another name for "static field."

like image 67
Zarwan Avatar answered Feb 11 '23 17:02

Zarwan