Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
What static means in Java: static fields shared by all objects, static final constants like Math.PI and System.out, static methods without this, when to use them, static factory methods (and why they beat constructors), and why main is static, plus Java 25 instance main methods.
kvi5hnuCode Sprout team member11 min readOn this page
Every main method you've written is marked static. This article finally explains what that modifier means, and how static fields and methods differ from the instance fields and methods of the previous articles.
In short: static members belong to the class, not to any individual object.
Static Fields
If you declare a field static, it isn't stored in each object. There's exactly one copy of the field, shared by the whole class.
Say each employee needs a badge number, and no two employees may share one. That calls for two fields of different kinds: an instance field badge that each object stores for itself, and a static counter nextBadge that remembers which number to hand out next:
class Employee {
private static int nextBadge = 1;
private int badge;
...
}
Create 250 employees and memory holds 250 separate badge values, yet still a single nextBadge. The counter lives with the class itself, so it is there before the first Employee is created and stays there if none ever is.
The constructor copies the counter into the new object and then moves the counter on:
badge = nextBadge;
nextBadge++;
When you construct omar, this effectively does:
omar.badge = Employee.nextBadge;
Employee.nextBadge++;

Some languages call static fields class fields, which describes them better. The word "static" is a historical holdover from C and C++ (see the note at the end of the static methods section).
Static Constants
Static variables are rare, but static constants are common. The Math class defines:
public class Math {
...
public static final double PI = 3.14159265358979323846;
...
}
You access it as Math.PI. If static were omitted, PI would be an instance field: you'd need a Math object to access it, and every Math object would have its own copy of the same value.
Another static constant you've used many times is System.out:
public class System {
...
public static final PrintStream out = ...;
...
}
Public fields are a bad idea because anyone can modify them, but public constants (public static final) are fine. Since out is final, nobody can assign another stream to it:
System.out = new PrintStream(...); // ERROR: cannot assign a value to final variable out
Constants of mutable types need care: public static final int[] PRIMES = {2, 3, 5}; can't be reassigned, but anyone can change PRIMES[0]. Use immutable types (List.of(2, 3, 5)) for public constants.
Static Methods
Static methods don't operate on objects. For example, Math.pow is static:
Math.pow(x, a) // computes x^a
It uses no Math object to do its job. In other words, a static method has no implicit parameter: there's no this.
Consequently, a static method of Employee can't access the instance field badge: there's no object whose badge it could mean. But it can access static fields:
public static int takeBadge() {
int r = nextBadge; // obtain next available badge
nextBadge++;
return r;
}
Call it with the class name:
int n = Employee.takeBadge();
Trying to use an instance field from a static method is a compile error:
error: non-static variable badge cannot be referenced from a static context
Could you drop static from takeBadge? Yes, but then you'd need an Employee object to call it, even though it doesn't use one.
When to make a method static
Use a static method when:
- It doesn't need the object's state, because everything it needs comes from its explicit parameters (
Math.pow,Integer.parseInt,Arrays.sort). - It needs only static fields of the class (
Employee.takeBadge).
Classes consisting only of static methods, such as Math, Arrays, Collections and Objects, are called utility classes. They usually have a private constructor so nobody can create pointless instances of them.
Static Factory Methods
Another common use of static methods is constructing objects. You've seen LocalDate.now() and LocalDate.of(...). The NumberFormat class obtains formatters for different styles like this:
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
NumberFormat percentFormatter = NumberFormat.getPercentInstance();
double x = 0.375;
System.out.println(currencyFormatter.format(x)); // prints $0.38 (in the US locale)
System.out.println(percentFormatter.format(x)); // prints 38%
Why doesn't NumberFormat just use constructors? There are three reasons to prefer a factory method:
- A factory method has a descriptive name. Every constructor carries the class name, so two constructors with the same parameter types couldn't be told apart.
getCurrencyInstanceandgetPercentInstancesay what you get. - A factory method may return a subclass. Both calls above really hand back a
DecimalFormat, a subclass ofNumberFormat(subclasses are the topic of the next part). The caller only relies on theNumberFormattype. - A factory method may reuse objects.
newalways allocates; a factory is free to return an existing instance.Integer.valueOf(100)returns the same cached object every time for small values (−128 to 127).
import java.text.NumberFormat;
import java.util.Locale;
public class Solution {
public static void main(String[] args) {
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat percentFormatter = NumberFormat.getPercentInstance(Locale.US);
double x = 0.375;
System.out.println(currencyFormatter.format(x));
System.out.println(percentFormatter.format(x));
System.out.println(currencyFormatter.getClass().getSimpleName());
Integer a = Integer.valueOf(100);
Integer b = Integer.valueOf(100);
Integer c = Integer.valueOf(1000);
Integer d = Integer.valueOf(1000);
System.out.println((a == b) + " " + (c == d));
}
}
$0.38
38%
DecimalFormat
true false
(a == b compares object identity: the two small values are the same cached object, while the large ones are separate objects. As with strings, compare wrapper objects with equals, never ==.)
Common naming conventions for factory methods: of (LocalDate.of, List.of), valueOf, from (conversions), parse (from text), getInstance/newInstance, create, and now for "current" values.
The main Method
You can call static methods without any objects: you never create a Math object to call Math.pow. That's exactly why main is static:
public class Application {
public static void main(String[] args) {
// construct objects here
...
}
}
When a program starts, no objects exist yet. The static main method runs and constructs the objects the program needs.
A Complete Example
public class Solution {
public static void main(String[] args) {
var staff = new Employee[3];
staff[0] = new Employee("Ines", 41000);
staff[1] = new Employee("Kofi", 58000);
staff[2] = new Employee("Wren", 63000);
for (Employee e : staff) {
System.out.println("name=" + e.getName() + ",badge=" + e.getBadge() + ",salary=" + e.getSalary());
}
int n = Employee.takeBadge(); // calls static method
System.out.println("Next issued badge=" + n);
}
}
class Employee {
private static int nextBadge = 1;
private String name;
private double salary;
private int badge;
public Employee(String n, double s) {
name = n;
salary = s;
badge = takeBadge();
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public int getBadge() {
return badge;
}
public static int takeBadge() {
int r = nextBadge; // obtain next available badge
nextBadge++;
return r;
}
public static void main(String[] args) { // unit test
var e = new Employee("Juno", 50000);
System.out.println(e.getName() + " " + e.getSalary());
}
}
name=Ines,badge=1,salary=41000.0
name=Kofi,badge=2,salary=58000.0
name=Wren,badge=3,salary=63000.0
Next issued badge=4
With the classes in separate files (the demo's Solution class saved as Solution.java), java Solution runs the application, and java Employee runs just the demo in Employee.main.
Instance Main Methods (Java 25)
Java 21 introduced, as a preview, a relaxed launch protocol, and Java 25 finalized it (JEP 512, together with compact source files). The main method no longer has to be public or static, and doesn't need a String[] parameter:
class Hello {
void main() {
System.out.println("Hello from an instance main method");
}
}
The launcher's rules:
- If the class has a
mainwith aString[]parameter, the launcher picks it; only otherwise does it pick amainwith no parameters. Whether a method isstaticdoesn't affect the choice, and a class can't declare a static and an instancemainwith the same parameter list anyway. (The first preview in Java 21 used a slightly different order that preferred static methods. Java 25 settled on this simpler rule.) mainmay bepublic,protectedor package-private, but notprivate.- If the chosen
mainisn't static, the class must have a non-private no-argument constructor. The launcher creates an instance and callsmainon it.
This makes beginner programs and small scripts less noisy. Production applications, frameworks and Java 21 code still use the classic public static void main(String[] args), so you'll see it everywhere. (On Java 21–24, the new forms required --enable-preview.)
Common questions
Can a static method call an instance method?
Only through an object: someEmployee.getName(). There is no this inside a static method, so a bare getName() doesn't compile. That's why main creates objects and then calls their methods.
When is a static field initialised?
When the class is initialised, which happens the first time it is really used: an instance is created, a static method is called, or a non-constant static field is accessed. Compile-time constants (static final int MAX = 10) are copied into the code that uses them, so reading them doesn't initialise the class.
Is static bad for testing?
Static methods that are pure functions (Math.max, Integer.parseInt) are easy to test. Static mutable state and static methods with side effects (reading the clock, calling a database) are hard to replace in tests. Pass such dependencies in as objects instead.
Why does Integer.valueOf(127) == Integer.valueOf(127) give true but 128 doesn't?
valueOf caches the values from −128 to 127 and returns the same object for them. Larger values create new objects, so == compares two different objects. Always compare wrapper objects with equals, or unbox them first.
Should I use a static nested class or a top-level class for helpers?
If the helper is used only by one class, a private static nested class keeps it close and hidden. If several classes use it, make it a top-level class, which is package-private unless it needs to be public.
Summary
- A static field has one copy per class, shared by all objects. It exists even when no objects do. Non-final static fields are rare global state; scrutinize them.
- Static constants (
public static final) likeMath.PIandSystem.outare common and fine, provided their type is immutable. - A static method has no
thisand can't access instance fields. Use one when a method needs only its parameters or static fields. Call it through the class name. - Static factory methods (
LocalDate.of,NumberFormat.getCurrencyInstance,Integer.valueOf) can have descriptive names, return subclass objects, and reuse instances. mainis static because no objects exist when a program starts. Any class may have amainfor demos.- Since Java 25,
mainmay also be an instance method withoutpublic,staticor parameters.
Practice Questions
An Employee class has private static int count = 0; and every constructor does count++. If 5 employees are created, what is the value of count, and how many count variables exist?
count is 5, and there's exactly one count variable, shared by the whole class.
Why does this fail to compile? class Circle { private double radius; public static double area() { return Math.PI * radius * radius; } }
area is static, so it has no this and no object whose radius it could use: "non-static variable radius cannot be referenced from a static context". Make area an instance method, or give it a parameter: static double area(double radius).
Give three reasons a class might offer a static factory method instead of (or in addition to) a public constructor.
(1) Factory methods have descriptive names (of, parse, getPercentInstance). (2) They can return an instance of a subclass or other implementation. (3) They can return cached or shared instances instead of always creating new ones (Integer.valueOf). They can also validate input before any object exists.
Why is main static in the classic Java launch protocol?
When the program starts, no objects exist. A static method can be called without an object, so the launcher can call main directly; main then creates the objects the program needs.
public static final List<String> COLORS = new ArrayList<>(List.of("red", "green")); Is COLORS a true constant?
No. final prevents reassigning COLORS, but the ArrayList is mutable: any code can call COLORS.add("blue"). Use an immutable list: public static final List<String> COLORS = List.of("red", "green");.
Previous: Java Encapsulation: Accessors, Mutators, private Methods and final Fields
Related reading
- Defining Your Own Classes in Java: Fields, Constructors and Methods
- Using Predefined Classes in Java: Objects, Object Variables and LocalDate
- Introduction to Object-Oriented Programming in Java
- Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays
- Java Arrays: Declaring, Initializing, for-each Loops and Copying

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.