Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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:

2

A 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
8

Notes

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

  • final — Forbids reassigning a variable, overriding a method or extending a class.
  • this — A reference to the current object — the one whose method or constructor is running.
  • class — Declares a class — a description of objects: their fields and methods.

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.

Thanks for reading!

Donate to the site — we work hard for you.