In Java, the static
keyword is used to indicate that a member belongs to the class itself, rather than to instances of the class. This means:
- A static variable is shared across all instances of the class.
- A static method can be called without creating an object.
- A static block runs once when the class is loaded.
- A static class (nested) can be used without an instance of the outer class.
🔹 What Is a Static Variable?
A static variable is also known as a class variable. It is initialized only once, at the time of class loading, and shared among all objects of that class.
✅ Example:
public class Student {
static String college = "ABC University"; // static variable
String name;
Student(String name) {
this.name = name;
}
void display() {
System.out.println(name + " studies at " + college);
}
public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
s1.display(); // Alice studies at ABC University
s2.display(); // Bob studies at ABC University
// Changing static variable
Student.college = "XYZ Institute";
s1.display(); // Alice studies at XYZ Institute
s2.display(); // Bob studies at XYZ Institute
}
}
🛠️ How to Set a Static Variable
You can set a static variable in three ways:
- At declaration:
static int count = 0;
2. Inside a static block (for complex initialization):
static {
count = 100;
}
3. Using the class name:
Student.college = “New College”;
🧠 Key Points
- Static variables are memory-efficient.
- They are not tied to any object.
- You can access them using the class name directly.