Interview Q&A · Java · 4 questions in this topic

Static Members: Variables, Methods & Access Rules — Java Interview Q&A

All Java topics

Static members belong to the class, not to any instance. That single fact explains every rule about them — including why static methods cannot touch instance state. Part of Methods & Constructors · 294 questions in the Java bank.

What are static blocks and static initialisers?

Answer

A static block (static { ... }) is initialisation code that runs exactly once, when the class is first loaded and initialised — before any constructor or main() runs, and in the textual order the blocks appear. It is the place for static-field setup too complex for a one-line assignment. The sibling concept, an instance initialiser block ({ ... }), runs once per object, before each constructor body.

Example

Example.javajava
class Config {
    static final Map<String, String> DEFAULTS = new HashMap<>();
    static {
        DEFAULTS.put("mode", "prod");   // runs once, at class-load time
    }
}

Can static methods access instance variables?

Answer

No — not directly. A static method runs without any object, so there is no this and no instance state to read. Attempting it fails compilation with "non-static variable cannot be referenced from a static context". A static method can still use instance state if you hand it an object explicitly and qualify the access (obj.field).

Example

Example.javajava
class A {
    int x = 1;
    static void f(A a) { System.out.println(a.x); } // legal: via a reference
    // static void g() { System.out.println(x); }    // illegal
}

How do we access static members?

Answer

Through the class name — ClassName.member — which signals that no instance is involved. Java also permits access through an object reference (obj.member), but compilers warn against it because it misleadingly suggests instance state. Static imports (import static ...) let you use static members unqualified.

Example

Example.javajava
Math.max(3, 7);          // class-name access (preferred)
import static java.lang.Math.max;
max(3, 7);               // static-import access

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits