The static keyword changes where and how long memory is allocated for a field or method: static members belong to the class itself rather than to any instance, and they are stored once in the JVM's method area, part of metaspace since Java 8, for as long as the class remains loaded.
Key Points: • Static fields are allocated once when the class is loaded and shared by every instance, unlike instance fields which get a fresh copy per object. • They live in the method area or metaspace, not on the per-instance heap allocation, which is why they persist independent of any object's lifecycle. • Because static fields are referenced by the class metadata itself, they stay reachable, and therefore ineligible for garbage collection, as long as the class loader that loaded the class is alive. • A static field holding a large collection, like a cache, is a classic memory leak source, since nothing ever dereferences it unless the code explicitly clears it. • Static methods don't allocate per-call state on the heap the way instance methods creating objects would, but any objects they create still follow normal heap and garbage collection rules.
Example: A static Map used as an application-wide cache stays in memory for the entire lifetime of the class, so if entries are added but never removed, memory usage grows continuously even though individual request objects have long since become unreachable.
Code Example:
public class ConfigCache {
private static final Map<String, String> cache = new HashMap<>();
public static void put(String key, String value) {
cache.put(key, value);
}
}Interview Tip: A concise interview answer is:
"Static fields are allocated once at the class level rather than per instance, and they live in the method area or metaspace for as long as the class stays loaded. That makes them a common source of memory leaks, since a static collection that keeps growing will never be garbage collected unless the code explicitly clears entries."