Java Static Methods
In this page:
What is a Static Method?
A static method belongs to the class itself rather than to any individual object, which means you can call it before a single instance of the class has ever been created. This makes static methods a natural fit for utility operations that don't depend on per-object state.
Example: What is a Static Method?
public class Main {
static void sayHello() {
System.out.println("Hello!");
}
public static void main(String[] args) {
sayHello(); // called with no instance created
}
}
Login to try C/C++/Java/PHP code in the editor
Calling Static Methods
You call a static method through the class name (e.g. Math.max(a, b)), not through an object reference — though Java will technically allow calling it via an instance too, that style is discouraged because it hides the fact that no instance state is actually being used.
Example: Calling Static Methods
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(3, 7)); // called through the class name
}
}
Login to try C/C++/Java/PHP code in the editor
Static vs Instance Methods
Because a static method has no this to refer to, it cannot directly read or write instance fields or call instance methods; it can only work with other static members and whatever is passed in as parameters. Trying to reference an instance field from a static method is a compile error, not a runtime one.
Example: Static vs Instance Methods
public class Main {
int instanceValue = 10;
static void staticMethod() {
// System.out.println(instanceValue); // would not compile: no 'this'
System.out.println("Static method running");
}
public static void main(String[] args) {
staticMethod();
}
}
Login to try C/C++/Java/PHP code in the editor
Accessing Variables
Static methods can freely read and modify static variables, which are shared across every instance of the class rather than being copied per object. That sharing is exactly why static state needs to be used carefully in multi-threaded code.
Example: Accessing Variables
public class Main {
static int counter = 0;
static void increment() {
counter++;
}
public static void main(String[] args) {
increment();
increment();
System.out.println(counter);
}
}
Login to try C/C++/Java/PHP code in the editor
Common Built-in Static Methods
Java's own standard library leans heavily on static methods for stateless utility work — Math.sqrt(), Integer.parseInt(), and Arrays.sort() are all static because none of them need an object's internal state to do their job.
Example: Common Built-in Static Methods
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(16));
System.out.println(Integer.parseInt("42"));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: