Junior — Middle
Where in memory are static variables of a class located in Java?
sobes.tech AI
Answer from AI
In Java, static class variables are stored in a memory area called the "Metaspace" starting from Java 8. Previously, they were located in "PermGen" (Permanent Generation). Metaspace is a part of memory allocated for storing class metadata, including static fields.
When a class is loaded, its static variables are placed in this area, and they exist as a single instance for all objects of that class.
Example:
public class Example {
public static int counter = 0;
public Example() {
counter++;
}
}
Here, counter is a static variable stored in the metaspace and shared among all instances of the Example class.