Sub topic 3
Static methods: behavior without an object
This chapter assumes you can write a class with fields, constructors, and instance methods, and that you know public and private. The previous chapter covered static fields. This one covers static methods: how to declare and call them, what happens when you call them, and how to decide whether a method should be static.
What a static method is
An instance method runs on a particular object. Inside it, this refers to that object, and the method can read and write that object's fields. A static method belongs to the class itself. It runs without any object, so it has no this.
You declare one with the static keyword, and you normally call it with the class name:
public class Geometry {
public static double circleArea(double radius) {
return Math.PI * radius * radius;
}
public static double clamp(double value, double min, double max) {
return Math.max(min, Math.min(max, value));
}
public static void main(String[] args) {
System.out.println(circleArea(2.0));
System.out.println(Geometry.clamp(15, 0, 10));
}
}This prints 12.566370614359172 and then 10.0. Inside Geometry, circleArea(2.0) needs no prefix. From another class you would write Geometry.circleArea(2.0). The 15, 0 and 10 passed to clamp are int values that widen to double, which is why the result prints as 10.0.
You have already used many static methods from the JDK: Math.abs, Integer.parseInt, String.valueOf, Arrays.sort, List.of, Objects.requireNonNull. None of them needs an object because everything they need arrives through their parameters.
Why `main` is static
The JVM starts your program by calling public static void main(String[] args). At that moment no objects of your class exist. If main were an instance method, the JVM would first have to construct an object, which would require it to know which constructor to call. Making main static removes that problem.
The mental model: no hidden parameter
Every instance method has one hidden parameter, the receiver, which you see as this. A static method has no such parameter. Everything it works on must be passed in explicitly, or come from static fields and other static members.
public class Account {
private double balance;
public void deposit(double amount) {
if (!isValidAmount(amount)) {
throw new IllegalArgumentException("Invalid amount: " + amount);
}
balance += amount;
}
public static boolean isValidAmount(double amount) {
return Double.isFinite(amount) && amount > 0;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
Account account = new Account();
account.deposit(50);
System.out.println(account.getBalance());
System.out.println(Account.isValidAmount(-5));
}
}The output is 50.0 and then false. deposit is an instance method because it changes balance, which belongs to one account. isValidAmount looks only at its argument, so it can be static. A caller can then check an amount before any Account exists. An instance method may call a static method of its own class without a prefix, as deposit does.
The diagram below summarizes how to choose between the two kinds.
How the call is resolved
For an instance method call such as shape.area(), the JVM looks at the runtime class of the object and picks the matching override. This is dynamic dispatch. A static call such as Geometry.circleArea(2.0) is different. The compiler decides which method to call, and the bytecode uses the invokestatic instruction, which has no receiver and no lookup on a runtime type. Two practical consequences follow:
- A static method can never be overridden. Chapter 10 of this tutorial covers what happens when a subclass declares a static method with the same signature.
- Overloading still works. Static methods can share a name if their parameter lists differ, and the compiler chooses by the argument types.
public class Printer {
static String describe(int n) {
return "int " + n;
}
static String describe(String s) {
return "String " + s;
}
public static void main(String[] args) {
System.out.println(describe(7));
System.out.println(describe("seven"));
}
}This prints int 7 and then String seven.
Calling a static method through an instance
Java allows you to write a static call with an object reference. The compiler ignores the object and uses its declared type:
public class NullCall {
static String hello() {
return "hello";
}
public static void main(String[] args) {
NullCall n = null;
System.out.println(n.hello());
}
}This prints hello and does not throw a NullPointerException, because the reference is never used. Most compilers and IDEs warn about this style. Always write NullCall.hello() so that readers can see the method is static.
Passing the object in: the "explicit this"
When a static method needs to work with objects, it takes them as parameters. This is common for operations that treat their inputs equally, where picking one as "the receiver" would be arbitrary:
class Point {
final double x;
final double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
static Point midpoint(Point a, Point b) {
return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}
}
public class MidpointDemo {
public static void main(String[] args) {
Point m = Point.midpoint(new Point(0, 0), new Point(4, 6));
System.out.println(m.x + ", " + m.y);
}
}The output is 2.0, 3.0. A static method in class Point may read the x and y of a Point argument, even if those fields are private. Access is controlled by the class, not by the object. What the method cannot do is use x on its own, without naming an object. The next chapter covers that rule.
Good candidates for static methods
A method is a good static candidate when all of these hold:
- It uses only its parameters, constants, and other static members.
- It gives the same result for the same arguments (it is a pure function).
- Nothing needs to override it or substitute it in a test.
Typical examples are math helpers, validation checks, conversions, parsing, and small helpers that support a single class. In the JDK, Math, Collections, Arrays, and Objects are collections of such methods. Chapters 7 and 8 show two further uses of static methods: factory methods that create objects, and utility classes.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Making a method static only to call it from `main` without creating an object | Compiles, but spreads logic that belongs on an object into static code | Create an object in `main` and call an instance method |
| Calling an instance method from `main` by its bare name | Compile error: non-static method cannot be referenced from a static context | Call it on an object, for example `new App().run()` |
| Calling a static method through an instance variable | Works, but misleads readers and triggers a warning | Use `ClassName.method()` |
| Writing a static method that changes static fields | Compiles, but creates hidden state shared by every caller | Pass data in and return results, or revisit the design |
| Expecting a subclass's static method to override the parent's | The parent's version still runs when called by the parent type | See the chapter on hiding |
Here is the second error in code:
public class App {
void run() {
System.out.println("running");
}
public static void main(String[] args) {
// run(); // compile error: no `this` in main
new App().run(); // correct: create an object first
}
}Static methods and testing
A static method with no hidden dependencies is easy to test. You call it with arguments and compare the result:
public class MathChecks {
public static void main(String[] args) {
if (Geometry.clamp(-3, 0, 10) != 0.0) {
throw new AssertionError("clamp below range failed");
}
if (Geometry.clamp(5, 0, 10) != 5.0) {
throw new AssertionError("clamp inside range failed");
}
System.out.println("ok");
}
}This uses the Geometry class from earlier and prints ok. Trouble starts when a static method reaches for something outside its parameters, such as the system clock, a file, a database connection, or a mutable static field. You cannot replace that dependency with a fake in a test, because there is no object whose field you could swap. A method like static void sendReport() that opens a network connection is much harder to test than an instance method that receives a connection object. Chapter 13 returns to this trade-off.
Summary of the rules
- A static method belongs to the class and runs without an object, so it has no
this. - Call it as
ClassName.method(...). Inside the same class, the bare name works. - The compiler picks the method at compile time, using the declared type and overload resolution.
- Pass in everything the method needs, either as parameters or as static members.
- Prefer static for stateless helpers. Prefer instance methods for behavior tied to an object's state.
Exercise
Look at this class. Why does line (1) compile while line (2) does not, and how would you fix line (2)? public class Timer { private int ticks; void tick() { ticks++; } static void reset() { helper(); // (1) helper is declared static tick(); // (2) } static void helper() { } }
Show answer
Line (1) compiles because one static method may call another static method of the same class by its bare name. Line (2) fails because tick() is an instance method and needs a receiver object, but reset() is static and has no this. Fix it either by passing a Timer into reset (static void reset(Timer t) { t.tick(); }) or by making reset an instance method, which is the better choice if it is meant to change one timer's ticks.
Exercise
What does this program print, and why does it not throw an exception? public class Demo { static int twice(int n) { return n * 2; } public static void main(String[] args) { Demo d = null; System.out.println(d.twice(21)); } }
Show answer
It prints 42. The call d.twice(21) is a static call. The compiler resolves it using the declared type Demo and ignores the value of d, so the null reference is never dereferenced. Writing Demo.twice(21) is clearer and avoids the warning.
Exercise
Write a static method isPalindrome(String s) in a class Words that returns true when the string reads the same forward and backward, ignoring case. Return false for null. Then say why static is a reasonable choice here.
Show answer
public static boolean isPalindrome(String s) { if (s == null) { return false; } String lower = s.toLowerCase(); return new StringBuilder(lower).reverse().toString().equals(lower); } Static is reasonable because the result depends only on the argument, the method reads and writes no object state, and there is nothing a subclass or a test would need to replace.