The static Keyword
Site Admin
· 11 Sep 2026
· 13 views
Belongs to the Class, Not an Object
A static member belongs to the class itself and is shared by every object of that class. You may call it without creating an object.
Static Fields
class Counter {
static int totalCount = 0; // shared by all Counter objects
int instanceCount = 0; // belongs to each object
Counter() {
totalCount++;
instanceCount++;
}
}
Counter a = new Counter();
Counter b = new Counter();
System.out.println(Counter.totalCount); // 2 - shared
System.out.println(a.instanceCount); // 1 - only this object
System.out.println(b.instanceCount); // 1Static Methods
class MathUtils {
static boolean isEven(int n) { return n % 2 == 0; }
}
boolean result = MathUtils.isEven(8); // no object needed
Static Initialiser Block
Runs once when the class is first loaded:
class Database {
static String url;
static {
url = "jdbc:mysql://localhost/app";
// load settings, open things once
}
}Rules to Remember
- A static method cannot access instance fields directly (no object exists).
- Inside a static method,
thisis unavailable. - Static fields are initialised once and shared; be careful with them in multithreading.
- Use static for utility methods that do not depend on object state.
Key Points
- Static members belong to the class and are shared.
- Call them via the class name, not an instance.
- Static code cannot touch instance state.