The static keyword
Static fields, methods, constants, static blocks, nested classes and when to use each.
Instance fields belong to each object: every Student has its own name. But some data and behaviour belongs to the class as a whole: the total number of students, a shared constant like MAX_CLASS_SIZE, or a utility method like Math.sqrt that needs no object at all. That is what the static keyword is for.
Static fields: one copy per class#
Access static members through the class name: Visitor.totalVisitors. Java also lets you write c.totalVisitors, but that is misleading (it looks per-object), so IDEs warn about it.
Static methods#
A static method is called on the class, not an object. It is perfect for operations that need only their parameters:
You use static methods constantly: Math.max, Integer.parseInt, String.valueOf, Arrays.sort, List.of.
The static rules
- A static method cannot use
this, or access instance fields and methods directly, because there is no current object. - It can access other static members, and it can create objects and call their instance methods.
This explains a famous beginner error. main is static because the JVM must call it before any objects exist. If you want to call instance methods from main, create an object first.
Constants: static final#
A value that never changes and is shared by everyone should be static final. By convention, its name is UPPER_SNAKE_CASE:
final on a reference means the variable cannot point elsewhere, but the object itself may still be mutable. static final List<String> NAMES = new ArrayList<>(); can still have items added. Use List.of(...) for a truly fixed list.
Static initialiser blocks#
When a static field needs more than one line to set up, use a static { ... } block. It runs once, when the class is first initialised:
(Map and HashMap are covered in the Maps lesson.)
Static nested classes#
A class declared inside another class with static is a static nested class. It is just a normal class whose name is scoped inside the outer one, used to group helpers that only make sense together:
A non-static nested class (an inner class) is tied to an instance of the outer class and can read its fields. Inner classes are less common; prefer static nested classes unless you need that link. The Email.Builder from the previous lesson was a static nested class.
Utility classes#
A class that only groups static helpers, like Math or Arrays, is a utility class. Make it final and give it a private constructor so nobody creates pointless instances:
Static factory methods#
A popular alternative to constructors is a static method that returns a new object. Unlike constructors, it has a descriptive name and can return cached instances:
The JDK is full of these: List.of, Integer.valueOf, LocalDate.of, Path.of.
Static imports#
import static lets you use static members without the class prefix:
Use it sparingly: for well-known names such as JUnit's assertEquals it reads nicely, but overused it hides where things come from.
When should something be static?#
Be careful with mutable static fields (non-final shared state). They act like global variables: any code can change them, they make testing harder, and they are a source of bugs in multithreaded programs.
Common mistakes#
- Calling an instance method from
mainwithout an object: "non-static method cannot be referenced from a static context". - Making fields static "to fix" that error, which accidentally shares one value across all objects.
- Accessing static members through an instance (
obj.COUNT) instead of the class name. - Expecting a
static finalcollection to be unmodifiable.
What's next#
Our classes still expose their fields to anyone. Next, encapsulation and access modifiers show you how to protect an object's data and design a clean public API.
Check your understanding
Quick quiz
1.A class has
static int count;and you create three objects that each docount++in the constructor. What iscount?2.Why can't a static method use
this?3.When does a static initialiser block
static { ... }run?
Finished reading?
Mark this lesson complete to track your progress.