What is static in Java?
The static keyword in Java is used for memory management. It can be applied to:
- Variables (fields)
- Methods
- Blocks
- Nested classes
When a member is declared static, it belongs to the class, rather than to any specific instance (object).
Use Cases of static
| Keyword Used With |
Meaning |
static variable |
Shared among all objects of the class |
static method |
Can be called without creating an object of the class |
static block |
Used to initialize static variables |
static class |
Used for nested static classes (inside another class) |
Static Variable Example
class Student {
int rollNo;
String name;
static String college = "ABC College"; // Shared by all students
Student(int r, String n) {
rollNo = r;
name = n;
}
void display() {
System.out.println(rollNo + " " + name + " " + college);
}
}
public class StaticVarExample {
public static void main(String[] args) {
Student s1 = new Student(101, "John");
Student s2 = new Student(102, "Alice");
s1.display(); // Output: 101 John ABC College
s2.display(); // Output: 102 Alice ABC College
}
}
college is shared among all objects — saved in class memory once.
Static Method Example
class Utility {
static void greet(String name) {
System.out.println("Hello, " + name);
}
}
public class StaticMethodExample {
public static void main(String[] args) {
Utility.greet("Shahid"); // No need to create object
}
}
Static methods can be called using the class name directly.
Static Block Example
class StaticBlockExample {
static int value;
// Static block runs once when class is loaded
static {
value = 100;
System.out.println("Static block executed.");
}
public static void main(String[] args) {
System.out.println("Value: " + value);
}
}
Output:
Static block executed.
Value: 100
Static block is used to initialize static variables.
Static Nested Class Example
class Outer {
static class Inner {
void show() {
System.out.println("Inside static nested class.");
}
}
}
public class StaticNestedClassExample {
public static void main(String[] args) {
Outer.Inner obj = new Outer.Inner(); // No need of Outer class object
obj.show();
}
}
Key Rules of static
- A static method cannot access non-static (instance) variables/methods directly.
this and super keywords cannot be used in static context.
- Static members are loaded at class loading time.
Summary
| Static Type |
Use |
| Static Variable |
Shared across all instances |
| Static Method |
Call without object |
| Static Block |
One-time initialization of static data |
| Static Class |
Nested class without Outer class object |