static Keyword in Java
In this lesson: Learn static in Java — static variables, methods, blocks and nested classes — with memory diagram and output. In Hindi & English.
What does static mean
The static keyword makes a variable or method belong to the class itself, not to individual objects. A static member is shared by all objects, and you can use it through the class name without creating any object.
Static variables
class Counter {
static int count = 0; // shared by all objects
Counter() { count++; } // increases the shared count
}
// use:
new Counter(); new Counter(); new Counter();
System.out.println(Counter.count);
There is only one count, shared by every object. Each new object increases the same variable, so it correctly counts how many were created — accessed via the class name.
Static methods
class MathUtil {
static int square(int n) {
return n * n;
}
}
// call without an object:
System.out.println(MathUtil.square(5));
A static method is called on the class, not an object — MathUtil.square(5). This is why utility methods and main are static.
Static blocks
class Config {
static String appName;
static {
appName = "CodingEasily"; // runs once at class load
System.out.println("Static block ran");
}
}
A static { } block runs once when the class is first loaded, before any object exists. It is handy for setting up static variables that need more than a simple value.
static vs instance
| Point | static | instance |
|---|---|---|
| Belongs to | The class | Each object |
| Copies | One shared | One per object |
| Accessed via | Class name | Object |
| Needs an object | No | Yes |
When to use static
- Shared data that all objects use, like a counter or a constant.
- Utility methods that do not depend on object data, like
Math.max. - Constants, often combined as
static final.
Use static when something belongs to the class as a whole, not to one object.
Common mistakes
- Using instance variables in a static method. A static method has no object, so it cannot.
- Expecting per-object copies of a static variable. There is only one, shared by all.
- Overusing static. Too much static breaks object-oriented design; use it only when shared.
- Calling static via an object. It works but is confusing — call it via the class name.
Summary
staticmakes a member belong to the class, not each object.- A static variable is one shared copy across all objects.
- A static method is called on the class, without an object.
- A static block runs once when the class loads.
- Use static for shared data, utility methods and constants.
Next, control visibility with access modifiers, or organise code with Java methods.
Frequently Asked Questions
What does the static keyword do in Java?
static makes a variable or method belong to the class itself, not to individual objects. A static member is shared by all objects and can be used without creating one, via the class name.