The static Keyword

Lesson 0012 — 35 min read

static means "belongs to the class, not to an instance." Shared across all objects. Loaded once. Accessed via class name.

Static Variables (Class Variables)

A single copy shared by all instances. Initialized once when the class is loaded.

class Counter {
    static int count = 0;

    Counter() { count++; }

    static void displayCount() {
        System.out.println("Count: " + count);
    }
}

Counter c1 = new Counter();
Counter c2 = new Counter();
Counter.displayCount(); // 2
class Counter {
public:
    static int count;

    Counter() { count++; }

    static void displayCount() {
        cout << "Count: " << count << "\n";
    }
};

int Counter::count = 0;  // Definition outside class

Counter c1, c2;
Counter::displayCount(); // 2
class Counter:
    count = 0  # Class variable

    def __init__(self):
        Counter.count += 1

    @staticmethod
    def display_count():
        print("Count:", Counter.count)

c1 = Counter()
c2 = Counter()
Counter.display_count()  # 2

Static Methods

Belong to the class. Callable without an instance. Cannot access this/self directly.

class MathUtils {
    static int add(int a, int b) { return a + b; }
}

int r = MathUtils.add(5, 3); // 8
class MathUtils {
public:
    static int add(int a, int b) { return a + b; }
};

int r = MathUtils::add(5, 3); // 8
class MathUtils:
    @staticmethod
    def add(a, b): return a + b

r = MathUtils.add(5, 3)  # 8

Keypoint: Static methods can only access static members directly. To access instance members, they need an object reference.

Static Local Variables (C++)

Created once, persists across function calls. Initialized on first call, not each time.

void foo() {
    static int x = 0;  // Initialized only ONCE
    x++;
    cout << "x = " << x << "\n";
}

foo(); // x = 1
foo(); // x = 2
foo(); // x = 3

Since C++11, initialization of function-local static is thread-safe.

Static Blocks / One-Time Initialization

class Example {
    static int value;

    // Runs once when class is loaded
    static {
        value = 10;
        System.out.println("Static block executed.");
    }
}

System.out.println(Example.value);
// Static block executed.
// Value: 10
class Example {
public:
    static int value;

private:
    static int init() {
        cout << "Static init executed.\n";
        value = 10;
        return 0;
    }

    static int trigger;
};

int Example::value = 0;
int Example::trigger = Example::init();
// Safer: function-local static (init on first use)
class Example:
    # Class body runs ONCE at definition time
    print("Class body executed.")
    value = 10  # Class variable initialized once

print("Value:", Example.value)
# Class body executed.
# Value: 10

Keypoint: Python's class-body code runs at definition time — no special block needed. C++ needs workarounds; prefer "init on first use" via function-local static.

Interaction: Static vs Non-Static

A static method has no this pointer. To access instance members, create or receive an object.

class Example {
    int instanceVar = 10;

    static void staticMethod() {
        Example obj = new Example();
        System.out.println(obj.instanceVar);
    }
}
class Example {
public:
    int instanceVar = 10;

    static void staticMethod() {
        Example obj;
        cout << obj.instanceVar << "\n";
    }
};
class Example:
    def __init__(self):
        self.instance_var = 10

    @staticmethod
    def static_method():
        obj = Example()
        print(obj.instance_var)

Advantages

Code trace: What does this print?

class A {
    static int x = 0;
    A() { x++; }
}

A a1 = new A();
A a2 = new A();
System.out.println(A.x);

Can a static method access this in Java?

Notes

static Keyword :-

Belongs to class, not instance ; single copy in memory ; loaded once when class is loaded

What Can Be Static :-

a) Variables ⇒ shared across all objects (class variables)

b) Methods ⇒ called via class name ; no instance object required

c) Static blocks (Java) ⇒ runs once when class is loaded by JVM

d) Local variables (C++) ⇒ persists across function calls ; initialized once

Restrictions :-

a) Static methods cannot access instance variables or methods directly without an object reference

b) Static methods have no this or self reference

Primary source: Oracle Java Tutorials — Class Variables. Ask me anything that's unclear.

← Prev: Interfaces Next: Inner Classes →

Questions? Ask your agent — you can follow up on any concept, quiz answer, or how this applies to a specific coding problem. Review the Java glossary or syntax quick reference for a compressed overview.