Static keyword means βbelongs to the class, not to an instanceβ.
You can access static members without creating an object.
Static Usage Summary
Use With | Effect |
---|---|
Variable | Shared across all instances |
Method | Can be called without an object |
Block | Static initializer runs once when the class loads |
Class (nested) | Declared a static nested class |
Example
class Counter {
static int count = 0;
Counter() {
count++;
}
}
System.out.println(Counter.count);
// Value shared across all instances
class MathUtil {
static int square(int x) {
return x * x;
}
}
int result = MathUtil.square(5); // No object needed
class InitExample {
static { // Executes once when class is loaded
System.out.println("Class loaded");
}
}
class Outer {
static class Inner {
void show() {
System.out.println("Static Nested Class");
}
}
}
Outer.Inner obj = new Outer.Inner();
obj.show();
Tip
Mention static when asked about:
- utility classes (Math, Collections),
- shared variables,
- main() method: public static void main(β¦),
- why static methods canβt access instance members directly.
Parent: _Core