← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 7 of 10

Java Static Methods

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?

java
public class Main {
	static void sayHello() {
		System.out.println("Hello!");
	}
	public static void main(String[] args) {
		sayHello(); // called with no instance created
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		System.out.println(Math.max(3, 7)); // called through the class name
	}
}

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

java
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();
	}
}

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

java
public class Main {
	static int counter = 0;
	static void increment() {
		counter++;
	}
	public static void main(String[] args) {
		increment();
		increment();
		System.out.println(counter);
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		System.out.println(Math.sqrt(16));
		System.out.println(Integer.parseInt("42"));
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.