What is the use of static keyword?
The `static` keyword in Java is a non-access modifier that is applicable for fields, methods, blocks, and nested classes. It indicates that the member belongs to the class itself rather than to any specific instance of the class.
Core Concept
static members are class-level members. This means they are shared among all instances of the class and can be accessed directly using the class name, without needing to create an object of the class. They are initialized when the class is loaded into memory.
`static` Variables (Class Variables)
static variables are also known as class variables. There is only one copy of a static variable per class, regardless of how many objects are created. This single copy is shared by all objects of the class. They are useful for representing information that is common to all objects of a class, such as a company name or a counter.
class Employee {
static String companyName = "Tech Solutions Inc."; // Static variable
String name;
Employee(String name) {
this.name = name;
}
}
`static` Methods (Class Methods)
static methods belong to the class rather than the object. They can be invoked directly using the class name, without the need to create an object. A key restriction is that static methods can only directly access static variables and call static methods. They cannot use this or super keywords, nor can they directly access non-static (instance) members because instance members are tied to specific objects, which may not exist when a static method is called.
class MathOperations {
static int add(int a, int b) { // Static method
return a + b;
}
}
`static` Blocks
static initialization blocks are used to initialize static variables or to perform static setup logic when the class is loaded into the JVM. A class can have multiple static blocks, and they are executed in the order they appear in the class definition.
class MyClass {
static int staticVariable;
static { // Static block
System.out.println("Static block executed.");
staticVariable = 10;
}
}
`static` Nested Classes
A static nested class is a nested class that is declared static. It can be accessed directly using the outer class name without creating an instance of the outer class. Unlike inner classes, static nested classes cannot access the non-static members of the outer class directly. They are often used for grouping helper classes that don't need access to the outer class's instance members.
class OuterClass {
static int outerStaticVar = 100;
int outerInstanceVar = 200;
static class StaticNestedClass { // Static nested class
void display() {
System.out.println("Outer static variable: " + outerStaticVar);
// Cannot access outerInstanceVar directly without an OuterClass instance
}
}
}
Key Characteristics and Rules
- Belong to the Class:
staticmembers are associated with the class itself, not with any particular object instance. - Direct Access: They can be accessed directly using the class name (e.g.,
ClassName.staticVariableorClassName.staticMethod()) without creating an object. - Memory Management:
staticmembers are loaded into memory only once when the class is loaded, making them memory efficient when many objects share the same data or functionality. thisandsuper:staticmethods cannot usethisorsuperkeywords because they do not operate on an instance.- Access to Instance Members:
staticmethods cannot directly access non-static(instance) variables or methods of the class. To access them, an object of the class must be created first.
When to Use `static`
- Constants: For defining constants that are shared across all instances (e.g.,
Math.PI). - Utility Methods: For creating utility functions that don't require any instance-specific data (e.g.,
Math.max(),System.out.println()). - Factory Methods: To provide alternative ways of creating objects, often used in design patterns like Singleton.
- Singleton Pattern: The
statickeyword is fundamental for implementing the Singleton design pattern, ensuring only one instance of a class exists. - Counting Instances: To maintain a count of how many objects of a class have been created.