How does the static keyword work in Java?

Where is this copy stored?

The copy (static variable) is stored in the Permanent Generation section, but if you use Java8 the Permanent Generation section no longer exists.
The static variables and static methods are part of the reflection data which are class-related data and not instance-related.

How do the objects access that copy?

Every instance of class (object) that you have created has a reference to the class.

When is this copy created?

It is created at runtime when the class is loaded: this is done by the classloader of the JVM when the class is first referenced.

Static variables belong to the class, and not to instances of the class.
Your intuition is right – you have only one copy regardless of how many object you create.

You can access a static variable using the name of the class, like in this example:

class Static {

    static int staticField;

}

public class UseStatic {

    public static void main(String[] args) {

        System.out.println(Static.staticField);

    }
}

The static fields are useful to create some kind of class constants.

Finally, to easily initialize a static field of a specific class you can use Static Initialization Blocks.

Sources: University course on java, java official documentation

Leave a Comment