BhauAutomation

Java Static Keyword

The static keyword in Java is used to define variables, methods, blocks, and nested classes that belong to the class rather than an instance of the class. Static members are shared across all objects of the class.

📘 Topic: Core Java / OOPs
Read time: 8 min
📊 Level: Intermediate
Focus: Class-level Members
📖 Overview

What is Static Keyword in Java?

Static is a non-access modifier in Java that indicates that a particular member (variable, method, block, or nested class) belongs to the class itself rather than to instances (objects) of the class. Static members are shared across all objects of the class.

Example: Static variable shared by objects

class Demo {
    static int count = 0;
    
    Demo() {
        count++;
    }
    
    public static void main(String[] args) {
        Demo obj1 = new Demo();
        Demo obj2 = new Demo();
        Demo obj3 = new Demo();
        System.out.println("Total objects created: " + Demo.count);
    }
}
📊 Static Variables

Static Variables (Class Variables)

Static variables are shared across all instances of a class. They are initialized only once at the start of execution and memory is allocated only once. Static variables are also known as class variables.

class Employee {
    private int empId;
    private String name;
    private static String companyName = "BhauAutomation";
    private static int counter = 0;
    
    Employee(String name) {
        this.empId = ++counter;
        this.name = name;
    }
    
    void display() {
        System.out.println("ID: " + empId + ", Name: " + name + ", Company: " + companyName);
    }
}
⚙️ Static Methods

Static Methods (Class Methods)

Static methods can be called without creating an instance of the class. They can only access static variables and static methods directly. They cannot access instance variables or instance methods directly (without object reference).

class MathUtils {
    static int add(int a, int b) {
        return a + b;
    }
    
    static int multiply(int a, int b) {
        return a * b;
    }
    
    static double circleArea(double radius) {
        return Math.PI * radius * radius;
    }
}

// Usage
int sum = MathUtils.add(10, 20);
int product = MathUtils.multiply(5, 6);
double area = MathUtils.circleArea(7.5);
🔧 Static Block

Static Block (Static Initializer)

Static block is used to initialize static variables. It is executed when the class is first loaded into memory, before any static method is called or any object is created. Multiple static blocks are executed in order.

class DatabaseConfig {
    static String url;
    static String username;
    static String password;
    
    static {
        // Static block for initialization
        url = "jdbc:mysql://localhost:3306/mydb";
        username = "root";
        password = "secret";
        System.out.println("Static block executed - Database config loaded");
    }
    
    static void display() {
        System.out.println("URL: " + url);
        System.out.println("Username: " + username);
    }
}
📁 Static Nested Class

Static Nested Class

A static nested class is a class defined inside another class with the static modifier. It can access only static members of the outer class. It can be instantiated without an instance of the outer class.

class Outer {
    private static String message = "Hello from Outer";
    private String nonStaticMsg = "Non-static";
    
    static class StaticNested {
        void display() {
            System.out.println("Accessing static member: " + message);
            // Cannot access non-static member of outer class
            // System.out.println(nonStaticMsg); // Error!
        }
    }
}

// Usage
Outer.StaticNested nested = new Outer.StaticNested();
nested.display();
🔧 Uses

Uses of Static Keyword

📊 Static Variables (Class Variables)

class Counter {
    static int count = 0;
    Counter() { count++; }
}

⚙️ Static Methods (Utility Methods)

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

🔧 Static Blocks (Initialization)

class Init {
    static { 
        System.out.println("Loaded"); 
    }
}

📁 Static Nested Classes

class Outer {
    static class Inner {
        void show() { }
    }
}
✅⚠️ Pros & Cons

✅ Advantages

Memory-efficient as static members are shared among all objects (only one copy in memory)

Access class members without creating an object (convenient for utility methods)

Useful for constants (static final) and utility methods like Math.pow(), Math.sqrt()

Static blocks allow complex initialization of static variables

⚠️ Limitations

Static members cannot access instance variables or instance methods directly

Overuse can lead to tightly coupled code and reduced testability

Not suitable for polymorphic behavior (cannot be overridden)

Static methods cannot be overridden (method hiding occurs instead)

💻 Complete Example

Complete Static Keyword Example

class Student {
    // Static variables
    private static String college = "BhauAutomation College";
    private static int studentCount = 0;
    
    // Instance variables
    private int rollNo;
    private String name;
    
    // Static block (executed once when class is loaded)
    static {
        System.out.println("Student class loaded - College: " + college);
        studentCount = 0;
    }
    
    // Constructor
    Student(String name) {
        this.rollNo = ++studentCount;
        this.name = name;
    }
    
    // Static method
    static void displayCollegeInfo() {
        System.out.println("College: " + college);
        System.out.println("Total Students: " + studentCount);
        // Cannot access instance variables here (rollNo, name)
    }
    
    // Instance method
    void displayStudentInfo() {
        System.out.println("Roll No: " + rollNo + ", Name: " + name);
        // Can access static variables here
        System.out.println("College: " + college);
    }
    
    // Static nested class
    static class Department {
        static String deptName = "Computer Science";
        
        void displayDept() {
            System.out.println("Department: " + deptName);
            // Can access static variables of outer class
            System.out.println("College from nested class: " + college);
        }
    }
}

public class StaticDemo {
    public static void main(String[] args) {
        // Access static method without object
        Student.displayCollegeInfo();
        
        // Create objects
        Student s1 = new Student("Alice");
        Student s2 = new Student("Bob");
        Student s3 = new Student("Charlie");
        
        System.out.println("\n--- Student Details ---");
        s1.displayStudentInfo();
        s2.displayStudentInfo();
        s3.displayStudentInfo();
        
        System.out.println("\n--- Static Nested Class ---");
        Student.Department dept = new Student.Department();
        dept.displayDept();
    }
}
🏆 Best Practices

Best Practices for Static Keyword

Use static members only when data/behavior truly belongs to the class, not instances

Declare constants as static final with UPPER_CASE naming convention

Keep utility methods (like Math class) in separate static-only helper classes

Avoid using static for mutable shared data in multi-threaded environments (use synchronization)

Use static blocks for complex static initialization logic

Prefer instance methods over static methods unless the method doesn't depend on object state