In OOP, most members (fields and methods) belong to a specific object instance. Each object has its own copy of instance variables. Static Members, however, belong to the class itself. There is only one copy, shared across ALL instances.
A static variable is shared by every object of the class. Changing it through one object changes it for all objects.
class Student {
String name;
static int totalStudents = 0; // Shared across ALL Student objects
Student(String name) {
this.name = name;
totalStudents++; // Incremented for every new student
}
}
Student s1 = new Student("Alice"); // totalStudents = 1
Student s2 = new Student("Bob"); // totalStudents = 2
System.out.println(Student.totalStudents); // 2 (accessed via class name)
Use Cases: Counters (tracking how many objects have been created), configuration constants, shared caches.
A static method can be called without creating an object. It can only access other static members (not instance variables or instance methods).
class MathUtils {
static double circleArea(double radius) {
return Math.PI * radius * radius;
}
}
double area = MathUtils.circleArea(5.0); // No object needed
Use Cases: Utility functions (Math.sqrt, Collections.sort), factory methods, main() method in Java.
A static initializer block runs once when the class is first loaded into memory, before any object is created.
class Config {
static Map settings;
static {
settings = new HashMap();
settings.put("timeout", "30");
}
}
main() is StaticThe main() method in Java is static because the JVM needs to call it before any objects exist. It's the entry point of the program, and at that point, no instances have been created yet.