Static Keyword (Methods, Variables, Blocks) in Java
What is static Keyword in Java?
The static keyword is used to create class-level members, meaning:
- They belong to the class rather than an instance (object)
- They are shared among all objects of the class
- Can be accessed without creating an object
Static Variables
A static variable is shared across all instances of the class.
class Counter {
static int count = 0; // static variable
Counter() {
count++;
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
new Counter(); // Count: 1
new Counter(); // Count: 2
new Counter(); // Count: 3
}
}
Note: The value of count is shared and incremented across all objects.
Static Methods
- Belong to the class, not an instance
- Can be called without an object
- Cannot access non-static members directly
class MathUtils {
static int square(int x) {
return x * x;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(MathUtils.square(5)); // Output: 25
}
}
Inside static methods, you cannot use this or call non-static methods/fields directly.
Static Blocks
Static blocks are used to initialize static variables. They run once when the class is first loaded.
class App {
static int configValue;
static {
System.out.println("Static block running...");
configValue = 42;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(App.configValue); // Triggers static block
}
}
Output:
Static block running...
42
Summary Table
Feature | Description |
---|---|
static variable |
Shared across all instances |
static method |
Belongs to class, no object needed |
static block |
Executes once when class is loaded |
When to Use static
Use Case | Example |
---|---|
Shared config/constants | static final double PI = 3.14; |
Utility/helper methods | Math.sqrt() , Collections.sort() |
Class-level logic | Counters, cache management, ID generators |
"static makes things belong to the class itself, not any individual object."