Static Keyword in Java
The static keyword in Java marks a field, method, nested class, or initializer block as belonging to the class itself rather than to any individual object....
Class-Level Members with the Static Keyword
The static keyword in Java marks a field, method, nested class, or initializer block as belonging to the class itself rather than to any individual object. Static members exist before any object is created and persist for the lifetime of the class loader. This makes static appropriate for data shared across all instances, utility methods that do not need object state, constants, and factory methods.
Static Fields: Shared State A static field is allocated once in memory, regardless of how many objects of the class are created. All instances read and write the same variable. Classic uses include counters (how many objects have been created), shared configuration values, and constants declared with static final. The Math.PI constant is a well-known static final field.
Static Methods: No Object Required Static methods are called on the class name rather than on an instance: Math.abs(-5), Integer.parseInt("42"). They cannot access instance fields or call instance methods directly because they have no this reference. However, they can access other static fields and call other static methods. Static methods are ideal for utility functions—operations that only depend on their arguments, not on any object's internal state.
Static Initializer Blocks A static initializer block runs once when the class is first loaded, before any constructor runs. It is useful for complex initialization of static fields that cannot be expressed as a simple assignment. The syntax is simply the keyword static followed by a block of code: static { /* complex setup */ }.
Code Example: class Counter { static int count = 0; String name;
Counter(String name) { this.name = name; count++; // every new object increments the shared count }
static int getCount() { return count; } }
new Counter("a"); new Counter("b"); System.out.println(Counter.getCount()); // 2
Interview Tip: Interviewers test whether you know that static methods cannot be overridden in the traditional sense. A subclass can define a static method with the same signature, but this is called method hiding, not overriding. The version called depends on the declared type of the reference at compile time, not the actual object type at runtime—the opposite of true polymorphic method dispatch.