Static Methods in Java
Problem
A static method belongs to the class itself, so it can be called through the class name directly — it never needs an object to exist first, unlike an instance method.
Write a utility method that squares a number, and call it without ever creating an object.
Java Program
class MathUtils {
static int square(int n) {
return n * n;
}
}
public class StaticMethods {
public static void main(String[] args) {
int result = MathUtils.square(6); // called directly through the class, no object needed
System.out.println("Square of 6 is " + result);
}
}Output
Core Logic
Declaring square() as static lets it be called through the class name alone, since it doesn't need to read or change any particular object's fields.
- 1
static int square(int n)is declared directly onMathUtils, with thestatickeyword marking it as class-level rather than object-level. - 2
MathUtils.square(6)calls it directly through the class name — nonew MathUtils()is ever needed. - 3Because the method only works with the value passed in, it has no reason to depend on any object's state.
- 4The result is printed directly from the call's return value.
MathUtils.square(6) returns 36, printed as "Square of 6 is 36".Key Point: An instance method would require an object before it could be called at all — the whole point of making square() static is that no such object is ever necessary.
Key Concepts
Approach 2: Java 8
import java.util.function.Function;
public class StaticMethodReferenceDemo {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
// Captures the static method itself as a value
Function<Integer, Integer> squareFn = StaticMethodReferenceDemo::square;
System.out.println("Square of 6 is " + squareFn.apply(6));
}
}
Output
Core Logic
A static method can be referenced directly as a value using Java 8's method reference syntax, and stored in a functional interface variable instead of being called by name.
- 1
Function<Integer, Integer> squareFn = MathUtils::square;captures the static method itself as a value, usingClassName::methodNamesyntax. - 2
squareFnnow behaves like any otherFunction— it can be passed around, stored, or invoked later. - 3
squareFn.apply(6)invokes the referenced static method with6as its argument. - 4The result is identical to calling
MathUtils.square(6)directly — the method reference is just another way to invoke the same static method.
MathUtils::square wraps the static method as a Function<Integer, Integer>, and calling .apply(6) on it returns 36, same as before.Key Point: Method references are most useful when a static method needs to be passed somewhere expecting a functional interface, like a Stream's map() — calling it directly by name, as the primary approach does, is simpler when no such interface is involved.