static Keyword

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

The static keyword means that a variable or method belongs to the Class itself, rather than to any specific instance (object) of the class.

  • Static Variables: Shared across all instances of the class.
  • Static Methods: Can be called without creating an object of the class (e.g., Math.max()).

Concept

When you create objects of a class, each object gets its own copy of instance variables. However, if a variable is declared static, memory is allocated only once when the class is loaded, and all objects share that single variable.

Static Block

You can use a static {} block to initialize static variables. It is executed exactly once, when the class is first loaded into memory by the JVM, before any objects are created or any static methods are called.

Restrictions

Static methods cannot access non-static (instance) variables or call non-static methods directly, because non-static members require an object to exist. They also cannot use the this or super keywords.

Examples

class Counter {
    // Instance variable: unique to each object
    int instanceCount = 0;
    
    // Static variable: shared by all objects
    static int staticCount = 0; 
    
    public Counter() {
        instanceCount++;
        staticCount++;
    }
}

public class StaticExample {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        
        System.out.println("c1 instanceCount: " + c1.instanceCount); // 1
        System.out.println("c2 instanceCount: " + c2.instanceCount); // 1
        
        // Best practice is to access static via the Class name
        System.out.println("Total staticCount: " + Counter.staticCount); // 2
        
        // Static method call
        helperMethod();
    }
    
    static void helperMethod() {
        System.out.println("Called without instantiating StaticExample!");
    }
}

Interview Questions

Q: Can you override a static method?
A: No. Static methods belong to the class, not the object. If a child class defines a static method with the same signature as a parent’s static method, it is called Method Hiding, not overriding. Polymorphism (dynamic method dispatch) does not apply to static methods.

Q: Why is the main method in Java declared as static?
A: Because it is the entry point of the application. The JVM needs to call this method to start the program before any objects of the class have been created. If it were not static, the JVM would have to instantiate the class first, which would introduce ambiguity (which constructor to use?).