What is Static Keyword in Java?
In Java, static denotes that a particular member belongs to the class itself rather than to instances (objects) of the class. This allows sharing of variables and methods across all objects.
Example: Static variable shared by objects
class Demo {
static int count = 0;
public static void main(String[] args) {
Demo.count++;
System.out.println("Count: " + Demo.count);
}
}
Uses of Static Keyword
Create class-level variables shared across all objects.
class Counter {
static int count = 0;
void increment() {
count++;
}
}
Define utility methods that can be called without creating objects.
class Utils {
static void greet() {
System.out.println("Hello!");
}
public static void main(String[] args) {
Utils.greet();
}
}
Initialize static blocks for class-level initialization.
class InitExample {
static {
System.out.println("Static block executed");
}
public static void main(String[] args) {}
}
Create static nested classes.
class Outer {
static class Inner {
void show() {
System.out.println("Static nested class");
}
}
public static void main(String[] args) {
Outer.Inner obj = new Outer.Inner();
obj.show();
}
}
Advantages
Memory-efficient as static members are shared among objects.
Access class members without creating an object.
Useful for constants and utility methods.
Limitations
Static members cannot access instance variables or methods directly.
Overuse can lead to tightly coupled code.
Not suitable for polymorphic behavior.
Best Practices
Use static members only when appropriate.
Prefer constants as static final variables.
Keep utility methods in separate helper classes.
Avoid using static for mutable shared data in multithreaded code.