What is the static keyword used for in Java?
6 minbeginnerstatickeywords
Quick Answer
static binds a member to the class itself rather than to any instance. Static fields are shared across all instances, static methods can be called without an object and can't access instance members, and a static nested class doesn't hold an implicit reference to an outer instance.
Detailed Answer
static marks a member as belonging to the class, not to any particular instance:
- Static fields: one copy shared by all instances (e.g., a counter of how many objects were created).
class Counter {
static int instances = 0;
Counter() { instances++; }
}
- Static methods: callable via the class name, without an instance (
Math.max(a, b)); they cannot referencethisor instance fields directly, since there's no instance involved. - Static initializer blocks:
static { ... }runs once, when the class is first loaded, useful for one-time setup of static state. - Static nested classes: a nested class marked
staticdoesn't get an implicit reference to an enclosing instance (unlike a regular inner class), so it can be instantiated independently:new Outer.StaticNested(). - Static imports:
import static java.lang.Math.*;lets you callmax(a, b)instead ofMath.max(a, b).
Common use cases: utility/helper methods (Collections.sort), constants (static final), factory methods, and singleton implementations.