Understanding Static Keyword in Java

The static keyword in Java is used to create members that belong to the class itself rather than to any individual object. Static members are shared across all instances of the class.

Static Variables

class Counter {
    static int count = 0;

    Counter() {
        count++;
    }
}

Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.count); // Output: 2

Static Methods

class MathUtils {
    static int square(int n) {
        return n * n;
    }
}

int result = MathUtils.square(5); // called without creating an object

Static Blocks

class Config {
    static int version;
    static {
        version = 1;
        System.out.println("Static block executed");
    }
}

Static Nested Classes

class Outer {
    static class Inner {
        void show() {
            System.out.println("Inside static nested class");
        }
    }
}

Outer.Inner obj = new Outer.Inner();

Key Points About Static

  • Static members are loaded into memory once when the class is loaded, not per object
  • Static methods can only directly access other static members, not instance members
  • A static block runs once, automatically, when the class is first loaded by the JVM
The main() method in Java is declared static so that the JVM can call it directly, without first creating an object of the class.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course