Sub topic 2
Static fields: state shared by all instances
This chapter assumes you can write a class with fields, constructors, and methods. It also assumes you can create objects with new, use public and private, and read basic inheritance code. It covers what a static field is, where its value lives, how to read and write it, and the mistakes that come up most often.
Class-level versus object-level fields
A field declared without static is an instance field. Each object gets its own copy, so changing it on one object does not affect any other.
A field declared with static is a static field, also called a class variable. The class has exactly one copy, and every object of that class sees the same value. The copy exists whether you have created zero objects or a thousand.
| Property | Instance field | Static field |
|---|---|---|
| Copies | One per object | One per class |
| Exists before any `new` | No | Yes |
| Typical access | `obj.field` or `this.field` | `ClassName.field` |
| Typical use | Data that describes one object | Data that describes all objects, or the class itself |
A first example
The Counter class below gives each object its own id and tracks how many objects exist.
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 and then 2. Here is what happens:
- The first
new Counter()incrementscreatedfrom 0 to 1 and stores 1 in that object'sid. - The second
new Counter()increments the samecreatedto 2 and stores 2 in its ownid. second.getId()reads the per-object field, which is 2.Counter.getCreated()reads the shared field, which is also 2.
The two values are equal only because second happens to be the last object created. The first object's id is still 1.
Where the value lives
The Java Language Specification does not tell you where static fields must be stored in memory. Here is the usual picture for HotSpot, the most common JVM, and how it affects your code.
- Instance fields are stored inside each object on the heap.
- A static field is stored once, together with the runtime representation of the class. It is created when the JVM prepares the class for use.
- The static field stays alive as long as the class is loaded. In a normal application that means until the program ends.
Because the class holds the static field, objects that the field refers to cannot be garbage collected while the class is loaded. This matters for static collections, covered below.
Default values and initialization
You do not have to assign a static field. The JVM gives it a default value when the class is prepared.
| Type | Default |
|---|---|
| `int`, `long`, `short`, `byte` | `0` |
| `double`, `float` | `0.0` |
| `boolean` | `false` |
| `char` | `'\u0000'` |
| Any object reference | `null` |
You can also assign a value in the declaration, as created = 0 does above. That assignment runs once, when the class is initialized. The class is initialized the first time one of these happens:
- an instance is created,
- a static method is called,
- a non-constant static field is read or written.
Initializers in a class run in the order they appear in the source. Reading a field before its declaration in an initializer is a compile error.
public class Order {
// static int a = b + 1; // compile error: illegal forward reference
static int b = 5;
static int a = b + 1; // a is 6
}Static blocks and the full initialization order are covered in a later chapter. For now, remember that a static initializer runs once per class, not once per object.
Accessing static fields
Use the class name. It tells the reader that the value is not tied to one object.
System.out.println(Counter.getCreated());Java also lets you reach a static field through an object reference. That compiles, but it is misleading, and most compilers and IDEs warn about it.
public class Visits {
static int total = 0;
public static void main(String[] args) {
Visits a = new Visits();
Visits b = null;
a.total++; // really Visits.total++
System.out.println(Visits.total); // 1
System.out.println(b.total); // 1, no NullPointerException
}
}b.total works even though b is null. The compiler uses only the declared type of b to find the field, and it never follows the reference. Code like this makes readers think total belongs to a or b, so avoid it.
Inside the class itself, you can use the bare name (created) or the qualified name (Counter.created). Both mean the same thing. A qualified name is clearer when the class also has a local variable or parameter with a similar name.
Visibility
Static fields follow the same access rules as instance fields. The usual guidance is the same too: keep mutable static fields private and expose them through methods. In Counter, outside code can read created through getCreated() but cannot set it to a wrong value.
A public static field that is not final is global mutable state. Any code in the program can change it, and you cannot enforce any rule about its value. Constants (static final) are a different case and get their own chapter.
Static fields and inheritance
A subclass does not get its own copy of a superclass's static field. There is one field, reachable through any class in the hierarchy.
class Base {
static int shared = 0;
}
class Child extends Base {
}
public class InheritDemo {
public static void main(String[] args) {
Child.shared = 5;
System.out.println(Base.shared); // 5
}
}Child.shared and Base.shared name the same storage. If you want a separate count for each subclass, you need a separate field in each, or a different design such as a Map keyed by class.
If a subclass declares a static field with the same name as one in the superclass, the subclass field hides the superclass field. Both exist, and which one you get depends on the class name or declared type you use. Avoid this. It is confusing, and it is the same rule that makes static methods hidden rather than overridden, which a later chapter covers.
Common errors
- Per-object data made static. If every object should have its own
nameorbalance, the field must be an instance field. Making it static means every object sees the last value written. - Counting with
createdinstead of copying it. InCounter,id = created;copies the value at construction time. If you storedcreateditself in a method likegetId(), every object would report the latest count. - Accessing through an instance.
obj.staticFieldhides the fact that the field is shared. UseClassName.staticField. - Forgetting that state persists. A static field keeps its value across the whole run. Unit tests that run in one JVM can affect each other if one test changes a static field and does not restore it.
- Unbounded static collections. A
static List<Object> cachethat only grows keeps every element reachable. Since the class is loaded for the life of the program, those objects are never collected. This is a common source of memory leaks. - Unsynchronized updates.
created++is a read, an add, and a write. If two threads run constructors at the same time, an update can be lost. The thread-safety chapter explains the fix, for exampleAtomicInteger.
Choosing between static and instance
Ask this question: if I create a second object, should it share this value or have its own?
- Share: a count of objects created, a default setting for the whole class, a lookup table that never changes.
- Own: anything that describes a single object, such as a name, a balance, or a position.
If you are unsure, start with an instance field. You can always move a field to static later, but code that depends on shared state is harder to untangle.
Exercises
Exercise
What does this program print, and why? public class Box { static int count = 0; int size; Box(int size) { this.size = size; count++; } public static void main(String[] args) { Box a = new Box(3); Box b = new Box(7); a.size = 10; System.out.println(b.size + " " + Box.count); } }
Show answer
It prints "7 2". The size field is an instance field, so changing a.size does not affect b.size, which stays 7. The count field is static, so both constructors incremented the same variable and Box.count is 2.
Exercise
A class declares static List<String> log = new ArrayList<>(); and every method call appends a message to it. Name two problems this can cause in a long-running, multithreaded program.
Show answer
First, the list grows without bound, and because a static field lives as long as the class is loaded, none of the messages can be garbage collected, which is a memory leak. Second, ArrayList is not thread-safe, so concurrent adds from several threads can lose elements or throw exceptions. Making the field private, bounding the list, and using a thread-safe structure or a logging framework addresses both.