Static Keyword in Java
Static Keyword in Java
The `static` keyword in Java is a modifier that can be applied to variables, methods, blocks,
and nested classes. It is used to define members that belong to the class rather than a
specific instance of the class. This means the member is shared among all instances of the
class and can be accessed without creating an object.
1. `static` Variables
A `static` variable is shared among all instances of a class. It is initialized only once, at the
start of the program, and is stored in the class's memory (not instance memory).
Key Points:
- Belongs to the class, not individual objects.
- Commonly used for constants or to maintain a shared state.
- Accessible directly using the class name.
Example:
class Counter {
static int count = 0; // static variable
Counter() {
count++;
}
void displayCount() {
System.out.println("Count: " + count);
}
}
2. `static` Methods
A `static` method belongs to the class and can be called without creating an instance of the
class. Static methods can only access static variables or other static methods directly.
Key Points:
- Cannot use `this` or `super` because they are instance-related.
- Used for utility or helper methods (e.g., `Math` class methods).
- Cannot override but can be hidden in subclasses.
Example:
class MathUtil {
static int square(int x) {
return x * x;
}
}
3. `static` Block
Key Points:
- Executes when the class is loaded into memory.
- Runs only once during the lifecycle of the application.
Example:
class StaticBlockDemo {
static int num;
static {
num = 10;
System.out.println("Static block executed. num initialized to " + num);
}
**Output:**
Key Points:
- Does not have access to non-static members of the enclosing class.
- Can access static variables and methods of the outer class.
- Useful for grouping classes logically and when the inner class doesn't need a reference to
the outer class.
Example:
class Outer {
static int outerValue = 100;
#### Example:
```java
class Example {
int instanceVar = 10;
2. **Utility Classes:**
Classes like `Math`, `Collections`, and `Arrays` use static methods to provide global utilities.
3. **Static Import:**
You can use `static` to import static members of a class to avoid prefixing the class name.
```java
import static java.lang.Math.*;