static fields
- Java course
- Intermediate
- Lesson 30/116
- 5 min
Learn class-level state with static fields.
static field
A static field belongs to the class, not to instances. All instances share the same static field. When one instance changes the value, others see it too. It is declared with the static keyword.
Example: class Counter { static int count = 0; }. Here count is static. Even if you create two Counter instances, there is only one count. It is accessed as Counter.count from the class name; instance access also works but is not recommended. Static fields are prepared when the class is loaded; they exist before any instance is created. This is useful for shared counters and configuration values.
Access via class name
Static fields are accessed through the class name, not through an instance. This clearly shows the field belongs to the class. The ClassName.field form is preferred.
Example: You access the count static field by writing Counter.count. Writing new Counter().count also works but is not recommended; because the static field belongs to the class, not the instance. Class-name access clarifies the code's intent. In Java, static fields like Math.PI and Integer.MAX_VALUE are called through the class name. This is the standard usage of static members.
Practice Add a static field to Counter
Define a class Counter. Add a static int count = 0 field. Write a void increment() method; its body runs count++. In main create two Counter instances, call increment on both and print the value of Counter.count.
Starter code
// Define the Counter class
// Add a static count field and increment method
// Call with two instances and print in mainSample solution
class Counter {
static int count = 0;
void increment() {
count++;
}
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
a.increment();
b.increment();
System.out.println(Counter.count);
}
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Two instances change the same static field. What happens?
- Each holds a separate value
- Both see the same value Correct answer
- A compile error occurs
- The static field is deleted
Explanation: A static field is shared; both instances see the same value.
2 Complete the static field definition
class Counter {
____ int count = 0;
}
class Counter {
static int count = 0;
}
Explanation: A static field belongs to the class.
3 Match the static field parts
| Term | Meaning |
|---|---|
static |
Keyword |
int count |
Field declaration |
Counter.count |
Class-name access |
shared |
Property |