🔹 static Keyword in Java
In Java, the static keyword is like a shared treasure chest 🗝️ — once created, it belongs to the class itself, not to individual objects.
👉 This means all objects can access it without creating multiple copies.
✨ What Does static Mean?
-
Non-static members → belong to objects (every object gets its own copy).
-
Static members → belong to the class (shared by all objects).
Think of it like a school notice board 🏫 – everyone can read it, but it’s placed only once for the whole class.
🛠 Uses of static Keyword in Java
1️⃣ Static Variables (Class Variables)
-
Shared across all objects.
-
Only one copy exists, no matter how many objects are created.
class Student {
String name;
static String college = "ABC College"; // Static variable
Student(String name) {
this.name = name;
}
void display() {
System.out.println(name + " - " + college);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Ravi");
Student s2 = new Student("Anita");
s1.display();
s2.display();
}
}
✅ Output:
Ravi - ABC College
Anita - ABC College
👉 Notice: College name is shared by all students!
2️⃣ Static Methods
-
Can be called without creating objects.
-
Can only access static variables (no instance variables directly).
class MathUtil {
static int square(int n) {
return n * n;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(MathUtil.square(5)); // No object needed
}
}
✅ Output:
25
3️⃣ Static Blocks
-
Used to initialize static variables.
-
Runs only once when the class is loaded into memory.
class Example {
static int num;
static {
num = 10;
System.out.println("Static block executed!");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Number: " + Example.num);
}
}
✅ Output:
Static block executed!
Number: 10
4️⃣ Static Classes (Nested Classes)
-
Java doesn’t allow top-level static classes,
but nested classes can be made static.
class Outer {
static class Inner {
void show() {
System.out.println("Static Nested Class");
}
}
}
public class Main {
public static void main(String[] args) {
Outer.Inner obj = new Outer.Inner();
obj.show();
}
}
🚀 Quick Recap
-
Static Variable → Shared across all objects.
-
Static Method → Can be called without objects.
-
Static Block → Runs once when class is loaded.
-
Static Class → Nested class that can exist without outer object.
🎯 Why Use static?
✔ Saves memory 🧠 (only one copy).
✔ Useful for utility methods (like Math.sqrt()).
✔ Makes code faster to access.
💡 Interview Tip: A common question is —
👉 “Can a static method access non-static variables?”
Answer: ❌ No, because non-static variables belong to objects, and static methods don’t need objects!