Java static Keyword
In this page:
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?
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-5)); // called via class name, no object needed
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: