Sub topic 2
Java Static Fields: State Shared by All Instances
Prerequisites
This chapter assumes you can define classes, create objects with new, write constructors, use public and private, and understand basic instance fields.
One field for the class
An instance field is stored separately in every object. A static field is stored once for the class. Every object of that class sees the same static field.
Use the static keyword in the declaration:
public class Counter {
private static int created = 0;
private final int id;
public Counter() {
created++;
id = created;
}
public int getId() {
return id;
}
public static int getCreated() {
return created;
}
public static void main(String[] args) {
new Counter();
Counter second = new Counter();
System.out.println(second.getId());
System.out.println(Counter.getCreated());
}
}The program prints:
2
2Each Counter object has its own id. The created field belongs to the Counter class, so both constructor calls update the same field.
Access a static field through the class name when possible:
Counter.getCreated();A static field can also be accessed inside the class by its simple name, as the constructor does with created.
| Member kind | Belongs to | Number of values | Typical access |
|---|---|---|---|
| Instance field | One object | One per object | `object.field` |
| Static field | The class | One per class | `ClassName.field` |
A class can have static fields even when no object exists. For example, Math.PI is available without creating a Math object.
What static state means
A static field is useful when a value describes the class as a whole:
- A counter of created objects
- A shared configuration value
- A cache shared by all objects
- A constant
- A registry of known objects
The field is initialized when the class is initialized, before the class is used. If no initializer is provided, Java gives the field its default value. Numeric fields start at 0, boolean fields start at false, and reference fields start at null.
The exact storage details are managed by the Java Virtual Machine. The important programming rule is that one class's static field is shared by all instances loaded by the same class loader. Different class loaders can create separate copies of the class and its static state.
Visibility and controlled updates
A static field is often declared private. This prevents unrelated code from changing it directly. Public methods can provide controlled access.
public final class VisitTracker {
private static int visits;
private VisitTracker() {
}
public static void recordVisit() {
visits++;
}
public static int totalVisits() {
return visits;
}
}The private constructor prevents callers from creating meaningless VisitTracker objects. The methods are static because recording and reading the total do not require a particular tracker object.
A public mutable static field is usually dangerous:
public static int visits;Any code can replace its value, so the class cannot protect its state. Prefer a private field and methods that express valid operations.
Shared state and threads
If several threads update a static field, a plain increment such as visits++ may lose updates. The increment reads the old value, adds one, and writes the result. Two threads can overlap these steps.
Use a thread-safe type when concurrent updates are possible:
import java.util.concurrent.atomic.AtomicInteger;
public final class IdGenerator {
private static final AtomicInteger NEXT = new AtomicInteger();
private IdGenerator() {
}
public static int next() {
return NEXT.incrementAndGet();
}
}Shared mutable static state also makes tests dependent on one another. A test that changes a static field may affect a later test. Reset state deliberately, or prefer an object whose lifetime and dependencies can be controlled.
Exercise
A class has 100 Report objects. It needs one shared count of all reports and one title for each report. Which fields should be static?
Show answer
The total report count should be static because it belongs to the class. The title should be an instance field because each report needs its own value.