Class-Level Variable Allocation in Java
Variables declared with the static keyword belong to the class rather than any specific object instance. This means memory allocation occurs only once, and all objects of that class share the same reference. Such variables are ideal for maintaining global states or counters across an application.
Declaration
Define a static field within a class to establish shared data.
public class InstanceTracker {
public static int activeInstances;
}Initialization
While static fields can be initialized directly at declaration, a static initialization block is typically used for more complex setup logic. This block executes when the class is first loaded into the JVM.
public class InstanceTracker {
public static int activeInstances;
static {
// Perform complex initialization logic here
activeInstances = 10;
}
}Accessing the value requires only the class name, such as InstanceTracker.activeInstances, eliminating the need to instantiate the class.