The static Keyword in Java
static binds a member to the class rather than to any instance, which changes when it is created, how it is accessed and what it can see.
-
Java Basics
- Introduction to Java
- Setting Up Java and Writing Your First Program
- Variables, Data Types and Literals in Java
- Type Casting and Type Conversion in Java
- Operators and Expressions in Java
- Input and Output in Java
- Comments, Keywords and Naming Conventions in Java
- Control Flow in Java: if, else and switch
- Loops in Java: for, while and do-while
- Methods
- Arrays and Strings
-
OOP
- Classes and Objects in Java
- Constructors in Java
- The this Keyword in Java
- The static Keyword in Java
- Encapsulation in Java
- Access Modifiers in Java
- Inheritance in Java
- Method Overriding and super in Java
- Polymorphism in Java
- Abstraction, Abstract Classes and Interfaces in Java
- Composition, Aggregation and Association in Java
- The Object Lifecycle in Java
- Core Java
- Exception Handling
-
Collections
- The Java Collections Framework
- List in Java: ArrayList, LinkedList, Vector and Stack
- Set in Java: HashSet, LinkedHashSet and TreeSet
- Map in Java: HashMap, LinkedHashMap and TreeMap
- How HashMap Works Internally in Java
- Queue and Deque in Java: ArrayDeque and PriorityQueue
- Iterators in Java
- Comparable and Comparator in Java
- Collections Utilities and Choosing the Right Collection
- Generics
- Java 8+
- Stream API
- Date and Time
- File and I/O
-
Multithreading
- Threads in Java: Processes, Runnable and Thread
- Thread Lifecycle in Java
- Synchronization in Java: synchronized and volatile
- Locks and Atomic Classes in Java
- Race Conditions and Deadlocks in Java
- The Executor Framework and Thread Pools in Java
- Future and CompletableFuture in Java
- Concurrent Collections in Java
- The Java Memory Model
- JVM and Memory
- Advanced Java
- Networking
- JDBC
- Testing
Definition
A static member belongs to the class, not to any object of it. There is exactly one copy, it exists as soon as the class is loaded, and it is reached through the class name.
Static fields
public class Registration {
private static int nextNumber = 1; // shared by every object
private final int number; // one per object
public Registration() {
this.number = nextNumber++;
}
public static int issued() {
return nextNumber - 1;
}
}new Registration();
new Registration();
System.out.println(Registration.issued()); // 2Every instance sees the same nextNumber, which is exactly what a shared counter needs.
Static methods
public final class Distance {
private Distance() { }
public static double kilometresToMiles(double km) {
return km * 0.621371;
}
}
double miles = Distance.kilometresToMiles(120);A static method depends only on its arguments. It cannot use this, cannot read instance fields, and cannot call instance methods without an object.
public class Example {
private int count = 5;
public static void wrong() {
// System.out.println(count); // compile error: no instance exists
}
public static void right(Example example) {
System.out.println(example.count); // fine, an object was supplied
}
}Static blocks
public class Configuration {
private static final Map<String, String> DEFAULTS;
static {
Map<String, String> values = new HashMap<>();
values.put("theme", "light");
values.put("pageSize", "20");
DEFAULTS = Map.copyOf(values);
}
}A static block runs once, when the class is initialised, in source order with the static field initialisers. Use it only when a constant needs more than a single expression.
Static nested classes
public class Cache {
private static class Entry { // no reference to the enclosing instance
final String key;
final String value;
Entry(String key, String value) {
this.key = key;
this.value = value;
}
}
}A static nested class is simply a class scoped inside another. Unlike an inner class it holds no hidden reference to the outer object, which makes it lighter and avoids accidental memory retention.
Static compared with instance
| Aspect | static | instance |
|---|---|---|
| Belongs to | The class | Each object |
| Copies | One | One per object |
| Created | On class initialisation | On new |
| Accessed by | ClassName.member | object.member |
Can use this | No | Yes |
| Overridable | No, only hidden | Yes |
Static methods are hidden, not overridden
class Parent {
static String name() { return "Parent"; }
}
class Child extends Parent {
static String name() { return "Child"; }
}
Parent p = new Child();
System.out.println(p.name()); // Parent - resolved from the declared typeStatic dispatch uses the compile time type; instance dispatch uses the runtime object. This example is a favourite in interviews because it looks like polymorphism and is not.
Constants
public static final int MAX_UPLOAD_MB = 25;
public static final List<String> ROLES = List.of("admin", "editor");static final is the idiom for a constant. Note that final only stops reassignment, so a static final mutable collection is still a shared mutable variable. Use an immutable factory such as List.of.
Common mistakes
- Reading an instance field from a static method and not understanding the error.
- Using static state for application data, which turns into a hidden global and breaks under concurrency and in tests.
- Expecting static methods to be polymorphic.
- Calling a static method through an instance reference, which compiles but misleads the reader.
- Declaring
static finalon a mutable object and treating it as immutable.
Best practices
- Make a method static only when it uses no instance state.
- Keep static mutable state out of application code; static should mean constant or stateless.
- Always call static members through the class name.
- Prefer a static nested class over an inner class unless the enclosing instance is genuinely needed.
- Combine
static finalwith genuinely immutable values.
Practice
- Write a class that counts how many objects of it have been created, and explain which field must be static.
- Why does calling an instance method from
mainwithout an object fail to compile? - Predict the output of the
ParentandChildexample, then makename()non static and predict again. - Explain the risk in
public static final List<String> ROLES = new ArrayList<>(); - Convert a utility class full of instance methods into a static one and describe what improves.
Conclusion
Use static for things that belong to the type rather than to an object: constants, stateless helpers and shared counters that are genuinely shared. Everything that describes a particular thing should stay an instance member.