Understanding the static
Keyword in Java
In Java, static
keyword is powerful feature used primarily for memory management. It is one of those small keywords with big implications—allowing us to create members that belong to class rather than instances of class.
This post explores how static
works with variables, methods, blocks, and nested classes, along with examples.
What is static
Keyword?
The static
keyword indicates that a particular member belongs to the class itself and not to instances of the class. That means:
- Static variables and methods are shared among all instances.
- Static blocks execute once, at the time of class loading.
- Static members can be accessed without creating object of class.
This makes static
especially useful for scenarios where you want to store or manipulate common/shared data.
1. Static Variable (Class Variable)
A static variable is also known as a class variable. Unlike instance variables (which get memory each time an object is created), a static variable:
- Gets memory only once at the time of class loading.
- Is shared by all objects of the class.
- Saves memory and promotes consistency in shared data.
Example Use Case:
-
collegeName
for all students -
companyName
for all employees
Benefits:
- Saves memory
- Easy to maintain shared values
class Employee {
static String company = "ABC";
int id;
String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " " + name + " " + company);
}
}
2. Static Method
A static method:
- Belongs to the class, not to an object.
- Can be called without creating an instance.
- Can only access static data members and static methods.
When to Use:
- Utility/helper methods like
Math.max()
- Factory methods
class Utility {
static int cube(int x) {
return x * x * x;
}
}
3. Static Block
A static block is used to initialize static variables. It's executed once, when the class is loaded before the main()
method runs.
Example:
class Demo {
static {
System.out.println("Static block executed.");
}
public static void main(String args[]) {
System.out.println("Main method executed.");
}
}
Output:
Static block executed.
Main method executed.
Conclusion
The static
keyword allows memory sharing and promotes consistent behavior across all objects, helping reduce redundancy and boost performance. It's especially useful when building utility classes, caching shared data, or initializing configurations during class loading.
Top comments (0)