JAVA - Zero to Hero / Object Oriented Programming (OOP)

Static Keyword

❔ What is static in Java?

The static keyword is used to create class-level members, meaning they belong to the class itself, not individual objects.

It can be applied to:

  • Variables

  • Methods

  • Blocks

  • Nested classes

💡 Real-Life Analogy

  • Think of a school name shared by all students.

  • You don’t need to store it for each student — it's common.

That’s exactly what static does — shares the same data across all objects.


🔗 Static Variable

A static variable is shared among all instances of a class.

class Student {
    static String school = "Greenwood High";  // shared

    String name;

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

    void display() {
        System.out.println(name + " from " + school);
    }
}

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

        s1.display();
        s2.display();
    }
}
Aanya from Greenwood High
Rahul from Greenwood High

✅ Both objects access the same static variable school.


📌 Static Method

A static method can be called without creating an object of the class.

class Utility {
    static void greet() {
        System.out.println("Hello from static method!");
    }
}

public class Main {
    public static void main(String[] args) {
        Utility.greet();  // no object needed
    }
}
Hello from static method!

⚠️ Rules of Static Methods

  • Can only access static variables/methods directly

  • Cannot use this or super

  • Best for utility/helper methods (like Math.sqrt())


🧱 Static Block

A static block is executed ****only once, when the class is first loaded.

class Demo {
    static {
        System.out.println("Static block called");
    }

    public static void main(String[] args) {
        System.out.println("Main method");
    }
}
Static block called
Main method

✅ Recap Table

Feature

Description

static variable

Shared by all objects

static method

Belongs to class, no object needed

static block

Runs once when class is loaded

Access

Use ClassName.memberName to access