← Back to Core Java Course | Chapter 7: OOP Core | Lesson 8 of 11

Java static Keyword

What is the static Keyword?

The static keyword ties a member to the class itself rather than to any individual object, so a static variable exists in exactly one place in memory and is shared by every instance of that class rather than copied per object.

Example: What is the static Keyword?

java
class Counter {
	static int total = 0;
}
public class Main {
	public static void main(String[] args) {
		Counter.total++;
		Counter c = new Counter();
		c.total++;
		System.out.println(Counter.total); // shared by all instances
	}
}

Static Methods

Static methods can be invoked directly through the class name without ever creating an object, which is why utility methods like Math.abs() are static — there's no meaningful per-object state for them to operate on.

Example: Static Methods

java
public class Main {
	public static void main(String[] args) {
		System.out.println(Math.abs(-5)); // called via class name, no object needed
	}
}

Static Blocks

A static initializer block runs exactly once, the first time the class is loaded by the JVM, before any object of that class is created — it's the right place to set up static state that's too complex for a simple one-line field initializer.

Example: Static Blocks

java
class Config {
	static int value;
	static {
		value = 42; // runs once, when the class loads
	}
}
public class Main {
	public static void main(String[] args) {
		System.out.println(Config.value);
	}
}

Static Nested Classes

A static nested class is defined inside another class but doesn't hold an implicit reference to an instance of the outer class, unlike a regular (non-static) inner class — you can create one without first creating an outer-class object.

Example: Static Nested Classes

java
class Outer {
	static class Nested {
		void show() {
			System.out.println("Inside static nested class");
		}
	}
}
public class Main {
	public static void main(String[] args) {
		Outer.Nested nested = new Outer.Nested();
		nested.show();
	}
}

Static vs Instance Elements

Instance variables belong individually to each object, while static variables are shared class-wide; instance methods can freely read and write both kinds, but static methods are restricted to only static members since they have no specific object context to work with.

Example: Static vs Instance Elements

java
class Demo {
	static int staticVar = 0;
	int instanceVar = 0;
	static void staticMethod() {
		staticVar++;
	}
	void instanceMethod() {
		staticVar++;
		instanceVar++;
	}
}
public class Main {
	public static void main(String[] args) {
		Demo.staticMethod();
		Demo d = new Demo();
		d.instanceMethod();
		System.out.println(Demo.staticVar);
	}
}

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.