Static Keyword in Java.

By Shakib Ansari | Date: Fri, Jun 6, 2025

Static Keyword Kya Hota Hai?

Java mein jab hum kisi cheez ko static bana dete hain, toh woh class-level par belong karti hai, object-level par nahi.

static members class ke saath directly related hote hain – bina object banaye use kiya ja sakta hai.

1. Static Variable

Definition:

static variable ek shared variable hota hai, jo class ke sabhi objects ke liye common hota hai.

Example:

class Student {
    String name;
    static String college = "DU"; // common for all students

    Student(String name) {
        this.name = name;
    }

    void show() {
        System.out.println(name + " studies in " + college);
    }
}

class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Rahul");
        Student s2 = new Student("Ravi");

        s1.show();  // Rahul studies in DU
        s2.show();  // Ravi studies in DU
    }
}

Key Point:

  • Static variable sirf ek baar memory mein aata hai.
  • Agar ek object static variable change karta hai, to sabhi mein reflect hota hai.

2. Static Method

Definition:

static method ko object ke bina call kiya ja sakta hai.

class MathUtil {
    static int square(int x) {
        return x * x;
    }
}
class Main {
    public static void main(String[] args) {
        System.out.println(MathUtil.square(5)); // Output: 25
    }
}

Important:

  • Static methods non-static members ko directly access nahi kar sakte.
  • Kyun? Kyunki static method class level pe hota hai, jabki non-static object level pe.

3. Static Block

Definition:

Static block ek aisa block hota hai jo class load hone ke time par ek baar run hota hai – object banne se pehle.

class Demo {
    static {
        System.out.println("Static Block Executed");
    }

    Demo() {
        System.out.println("Constructor Called");
    }
}
class Main {
    public static void main(String[] args) {
        Demo d = new Demo();
    }
}

Output:

Static Block Executed  
Constructor Called

Real-World Analogy:

  1. Static Variable: Ek school ka naam (sabhi students ke liye same)
  2. Static Method: Calculator app ka square button (har kisi ke phone mein same logic)
  3. Static Block: Ghar banne se pehle ek baar wiring ho jaati hai


About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments