static
Makes a field or method belong to the class itself rather than to each object.
Available since: Java 1.0
Syntax
static Type name; static Type method() { … }Examples
A static counter is shared by all objects:
class User {
static int count = 0;
String name;
User(String name) {
this.name = name;
count++;
}
}
void main() {
new User("Anna");
new User("Oleg");
IO.println(User.count);
}Output:
2A static method is called on the class name, without an object:
class MathUtils {
static int square(int x) {
return x * x;
}
}
void main() {
IO.println(MathUtils.square(7));
IO.println(Math.max(3, 8));
}Output:
49
8Notes
A static method cannot see the object's fields or this — it has no "current object". The error "non-static variable cannot be referenced from a static context" means a static method used an instance field or method.
Methods like Math.max(), Integer.parseInt(), List.of() are static, which is why they are called on the class name.
See also
Related recipes
In the tutorial
- Static fields and methods — The static keyword in Java: shared class fields, static methods, static final constants and calls through the class name.