Common Use Cases for static Fields: Constants and Counters
You'll learn: When and why to use static fields for constants, object counters, and shared application state.
Why Use static Fields?
Now that you understand static fields are shared across all instances of a class, let's explore their most practical applications. Think of static fields as information that belongs to the class itself rather than to individual objects.
Use Case 1: Constants
The most common use of static fields is for constants—values that never change and should be shared by everyone:
public class MathConstants {
public static final double PI = 3.14159;
public static final int MAX_SIZE = 100;
}
// Access via class name
double area = MathConstants.PI * radius * radius;
Why static for constants? Because constants don't need separate copies per object—everyone uses the same value. The final keyword prevents modification.
Use Case 2: Object Counters
Track how many instances of a class have been created:
public class Student {
private static int studentCount = 0;
private String name;
public Student(String name) {
this.name = name;
studentCount++; // Increment shared counter
}
public static int getStudentCount() {
return studentCount;
}
}
// Usage
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
System.out.println(Student.getStudentCount()); // 2
Every time a Student is created, the shared studentCount increases—like a visitor counter at a building entrance.
Use Case 3: Application-Wide State
Shared configuration or settings that apply to the entire program:
public class AppConfig {
public static boolean debugMode = false;
public static String version = "1.0";
}
Key Takeaway:
Use static fields for constants (with final), counters tracking class-wide information, and application-wide state that should be shared by all instances rather than duplicated per object.