4

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".

mustaccio
  • 18,234
  • 16
  • 48
  • 57
  • 2
    Related question about static initializer aka static block was quite nicely answered here: http://stackoverflow.com/questions/2943556/static-block-in-java/2943575#2943575 – Sva.Mu Aug 31 '15 at 21:56
  • 1
    Maybe you just misread the sentence. “static fields” and “class variables” are just synonyms, that’s all the words in parentheses want to tell you. You may read the sentence by mentally omitting the insertion or by replacing “static fields” with “class variables” and there will be no semantic difference. – Holger Sep 01 '15 at 09:36

2 Answers2

5

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."

Zarwan
  • 5,537
  • 4
  • 30
  • 48
3

A static member is a variable that belongs to the class as a whole, not a specific instance. It's initialized once, when the classloader loads the class.

E.g.:

public class MyClass {
    // Note the static modifier here!
    private static int someVariable = 7;
}

One common usecase for such variables is static final members of immutable types or primitives used to represent constants:

public class Human {
    public static final String SPECIES = "Homo sapiens";
    public static final int LEGAL_DRINKING_AGE = 21; // U.S centric code :-(
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350