Java static Members, Static Initializers and Static Imports (OCP 21)
static fields and methods for the OCP Java 21 exam: shared class state, accessing static members through the class or through a (even null) reference, why static code can't use instance members directly, static final constants, static initializers, and the rules and traps of static imports.
kvi5hnuCode Sprout team member8 min readOn this page
Every method you've written so far, except main, has been an instance method that works on one particular object. The static keyword makes a field or method belong to the class itself: there's exactly one copy, it exists without any object, and every object of the class shares it. This article covers static fields and methods, the rules for calling between static and instance code, constants, static initializers and static imports. All of them appear on the exam.
One copy for the whole class
public class Bike {
String id; // one per object
static int created; // one for the class
}
var b1 = new Bike();
b1.id = "B1";
b1.created = 1;
var b2 = new Bike();
b2.id = "B2";
b2.created = 2;
System.out.println(b1.id); // B1
System.out.println(b1.created); // 2 (the same variable as b2.created)
System.out.println(b2.id); // B2
System.out.println(Bike.created); // 2
Each object has its own id, but there's only one created, no matter which reference you reach it through.

Use static for:
- helper methods that need no object state, such as
Math.max,Arrays.sortandInteger.parseInt, so callers don't have to create an object first; - state shared by all instances, such as a counter or a cache, together with the methods that work on it;
- constants (
static final); - the entry point
main, which the JVM calls without creating an object. You can call it yourself, too:Other.main(new String[0]).
Accessing static members
The usual way is through the class name: Bike.created, Math.max(1, 2). Inside the class, the name alone is enough.
You can also access a static member through a reference. The compiler then uses only the reference's declared type and ignores the object, so even a null reference works:
Bike b = new Bike();
System.out.println(b.created); // reads Bike.created
b = null;
System.out.println(b.created); // still reads Bike.created: no NullPointerException
javac -Xlint warns "static variable should be qualified by type name". It's legal code, but it's misleading, and it's a classic exam trap. When you see a static member accessed through a variable, replace the variable with its declared type in your head.
Bike.created = 4;
Bike x = new Bike(), y = new Bike();
x.created = 6;
y.created = 5;
System.out.println(Bike.created); // 5: there is only one variable
Static vs. instance: who can call what
An instance member needs an object. A static method runs without one, so it has no this, and it can't use instance fields or call instance methods unless it has a reference to an object:
public class Station {
private String name = "Central";
static void open() { }
void announce() { System.out.println(name); }
public static void main(String[] args) {
open(); // fine: static calls static
announce(); // DOES NOT COMPILE: non-static method announce() cannot be referenced from a static context
System.out.println(name); // DOES NOT COMPILE: non-static variable name ...
System.out.println(this); // DOES NOT COMPILE: no this in a static context
var s = new Station();
s.announce(); // fine: called through a reference
System.out.println(s.name); // fine
}
}
Making announce static doesn't fix the problem, because then announce can't read the instance field name. Either make both static, or call the instance method through an object.
| From | Static member | Instance member |
|---|---|---|
| static method or static initializer | yes, directly | only through a reference: obj.m() |
| instance method or instance initializer | yes, directly | yes, directly (through this) |
The same applies to field initializers:
public class Gauge {
public static int count;
public int total;
public void add() { count++; } // instance code can use static state
public static double average = total / count; // DOES NOT COMPILE: instance field in static context
}
A common real-world pattern combines both: a static counter that every constructor updates.
public class Ticket {
private static int issued;
public Ticket() { issued++; }
public static int issued() { return issued; }
}
Static variable modifiers and constants
Static fields can use the same modifiers as instance fields: any access level, final, volatile and transient. A static final field is a constant. By convention, constants are named in UPPER_SNAKE_CASE:
public class Route {
private static final int MAX_STOPS = 40;
private static final String[] STOPS = new String[MAX_STOPS];
static void edit() {
MAX_STOPS = 50; // DOES NOT COMPILE: cannot assign a value to static final variable
STOPS[0] = "Depot"; // fine: the array's contents can change
STOPS = null; // DOES NOT COMPILE
}
}
As with every final variable, final stops reassignment, not mutation. A truly constant collection needs an unmodifiable type such as List.of(...) or Map.copyOf(...).
A static final field must be assigned exactly once: either in its declaration or in a static initializer. There are no "static constructors", and assigning it in a regular constructor doesn't compile.
Static initializers
A static initializer is a block marked static. It runs once, when the class is initialized (the first time it's actually used), and multiple blocks run in the order they appear in the file:
private static final int SECONDS_PER_MINUTE;
private static final int MINUTES_PER_HOUR;
private static final int SECONDS_PER_HOUR;
static {
SECONDS_PER_MINUTE = 60;
MINUTES_PER_HOUR = 60;
}
static {
SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
}
The first assignment of a static final field is allowed. Any later one isn't:
private static int a;
private static final int b;
private static final int c = 3;
private static final int d; // DOES NOT COMPILE: never assigned
static {
a = 1;
a = 10; // fine: a isn't final
b = 2;
c = 4; // DOES NOT COMPILE: already assigned
b = 5; // DOES NOT COMPILE: might already have been assigned
}
Use static initializers sparingly, mainly when a static field needs several statements to build, such as filling a lookup table. If you have one, put all the setup in a single block so the order is obvious. Chapter 6 shows exactly where static initialization fits in the full order of object creation.
Static imports
A normal import lets you use a type without its package name. A static import lets you use a static member without its class name:
import java.util.List;
import static java.util.Arrays.asList; // one static member
import static java.lang.Math.*; // all static members of Math
public class Imports {
List<String> names = asList("Ada", "Lin");
double r = sqrt(PI) + max(2, 3); // Math.sqrt, Math.PI, Math.max
}
The exam likes to test the mistakes:
import static java.util.Arrays; // DOES NOT COMPILE: a static import needs a member, not a class
import static java.util.Arrays.asList;
static import java.util.Arrays.*; // DOES NOT COMPILE: the order is import static
import static java.lang.Math.random(); // DOES NOT COMPILE: no parentheses
public class BadImports {
void m() {
Arrays.asList("one"); // DOES NOT COMPILE: Arrays itself was never imported
asList("one"); // fine
}
}
The last trap is the most common one. A static import brings in the member, not the class. To write Arrays.asList, you still need import java.util.Arrays;.
Name clashes
- A member declared in your own class (a method or field with the same name) takes priority over a statically imported one.
- If two static imports bring in fields or methods with the same name, the import lines themselves compile. The error comes when you use the name and the compiler can't choose: "reference to MAX_VALUE is ambiguous". For methods, normal overload resolution is tried first, so a clash only happens when both are equally good matches. A single static import (
import static java.util.Collections.max;) shadows same-named members from an on-demand one (import static java.lang.Math.*;), so then only the single import's methods are candidates.
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Long.MAX_VALUE;
public class Limits {
long m() { return MAX_VALUE; } // DOES NOT COMPILE: ambiguous
}
The fix is to write the class name in the code: Long.MAX_VALUE. In exam questions, the clashing name is almost always used, so the answer is "does not compile".
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Static imports date from Java 5. Java 25's module import declarations (
import module java.base;, article 3) import types, not static members, so they don't replaceimport static.
Exam traps from this article
A complete example
The program models a bike rental with a shared counter, a constant, a lookup table built in a static initializer, a static helper method and an instance method. It also shows when the class is initialized and what happens when a static method is called through a null reference.
import static java.lang.Math.max;
import static java.lang.Math.round;
import java.util.Map;
import java.util.TreeMap;
public class Solution {
static class Bike {
// One copy shared by every Bike: the class's own state.
private static int created;
static final int MAX_SPEED_KMH = 25; // compile-time constant
static final Map<String, Integer> PRICE_PER_HOUR;
// A static initializer runs once, when the class is first used.
static {
System.out.println(" [Bike class initialized]");
var prices = new TreeMap<String, Integer>();
prices.put("city", 3);
prices.put("cargo", 5);
prices.put("e-bike", 7);
PRICE_PER_HOUR = Map.copyOf(prices); // assigned exactly once
}
// One copy per object.
private final String id;
private final String type;
Bike(String type) {
created++; // instance code may use static state
this.id = "B" + created;
this.type = type;
}
// Static helper: needs no object, only its parameters and static state.
static int quote(String type, int hours) {
return PRICE_PER_HOUR.getOrDefault(type, 0) * max(1, hours);
}
static int created() {
return created;
}
// Instance method: uses this object's fields and may call static methods.
String describe(int hours) {
return id + " (" + type + ") for " + hours + " h = " + quote(type, hours) + " EUR";
}
}
public static void main(String[] args) {
System.out.println("Reading a compile-time constant:");
System.out.println(" max speed " + Bike.MAX_SPEED_KMH); // inlined: no initialization
System.out.println("First real use of Bike:");
System.out.println(" bikes so far: " + Bike.created());
var a = new Bike("city");
var b = new Bike("e-bike");
var c = new Bike("cargo");
System.out.println(a.describe(2));
System.out.println(b.describe(0));
System.out.println(c.describe(3));
System.out.println("bikes created: " + Bike.created());
// A static member accessed through a reference uses the reference TYPE, not the object.
Bike none = null;
@SuppressWarnings("static")
int viaNull = none.created();
System.out.println("through a null Bike reference: " + viaNull);
// Statically imported Math.round, with no Math. prefix.
System.out.println("average price: " + round((3 + 5 + 7) / 3.0) + " EUR/h");
System.out.println("price table: " + new TreeMap<>(Bike.PRICE_PER_HOUR));
}
}
Output:
Reading a compile-time constant:
max speed 25
First real use of Bike:
[Bike class initialized]
bikes so far: 0
B1 (city) for 2 h = 6 EUR
B2 (e-bike) for 0 h = 7 EUR
B3 (cargo) for 3 h = 15 EUR
bikes created: 3
through a null Bike reference: 3
average price: 5 EUR/h
price table: {cargo=5, city=3, e-bike=7}
Points to notice:
- Reading
Bike.MAX_SPEED_KMHprints25before the "initialized" line. The constant was copied intomainby the compiler, soBikewasn't initialized yet. - The first call to a static method,
Bike.created(), triggers the static initializer, and it runs only once. - Every constructor call increments the single
createdcounter, which the ids reflect. none.created()works even thoughnoneisnull. The@SuppressWarnings("static")only silences the lint warning.maxandroundare used withoutMath.because of the static imports at the top.
Common questions
Can a static method be overridden? No. A subclass can declare a static method with the same signature, but that hides the parent's method instead of overriding it. Which one runs depends on the reference type at compile time. Chapter 6 covers this.
Is a static field thread-safe?
No. Shared mutable static state needs synchronization, an AtomicInteger, or similar tools (Chapter 13). Prefer immutable static final data where you can.
Can a top-level class be static?
No. Only nested classes can be static (Chapter 7). "Static class" in conversation usually means a class with only static members and a private constructor, like Math.
Do I need static on interface constants?
Fields in an interface are implicitly public static final (Chapter 7).
Summary
staticfields and methods belong to the class: there's one copy, and no object is needed to use them. Instance members belong to each object.- Access static members through the class name. Access through a reference compiles, uses the declared type, and works even with
null. - Static code needs an object reference to use instance members. Instance code can use static members directly.
static finalconstants are assigned exactly once, in the declaration or a static initializer. Static initializers run once, in file order, when the class is first initialized.import staticimports members, not classes. Local declarations win over static imports, and clashing names fail only when used.
Practice quiz
Test yourself with the static members and static imports quiz: 10 exam-style questions with explanations.
Previous: Java Access Modifiers: private, Package, protected and public (OCP 21)
Next: Java Pass-by-Value, Returning Objects and Autoboxing (OCP 21)
Related reading
- Java Access Modifiers: private, Package, protected and public (OCP 21)
- Java Local and Instance Variables, Effectively Final and Varargs (OCP 21)
- Java Method Declarations: Access Modifiers, Specifiers, Return Types and Parameters (OCP 21)
- Java Period, Duration, Instant and Daylight Saving Time (OCP 21)
- Java Date and Time: LocalDate, LocalTime, LocalDateTime and ZonedDateTime (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.