Static Variables and Methods in Java — Class-Level Members

2 minute read

While instance members belong to each object, static members belong to the class itself — shared across all objects.


Static Variables (Class Variables)

class Employee {
    private String name;
    private double salary;
    static int employeeCount = 0;  // shared across ALL employees

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
        employeeCount++;  // incremented for every new object
    }
}
new Employee("Alice", 95000);
new Employee("Bob", 78000);
new Employee("Charlie", 82000);

System.out.println(Employee.employeeCount);  // 3

All three objects share the same employeeCount.

Heap
┌─────────────────────────────┐
│ Employee Class (shared)     │
│   employeeCount: 3          │
├─────────────────────────────┤
│ Employee Object 1           │
│   name: "Alice"             │
├─────────────────────────────┤
│ Employee Object 2           │
│   name: "Bob"               │
└─────────────────────────────┘

Static Methods

Static methods belong to the class — they cannot access instance variables or this.

class MathUtils {
    public static int max(int a, int b) {
        return (a > b) ? a : b;
    }

    public static double average(int... numbers) {
        int sum = 0;
        for (int n : numbers) sum += n;
        return (double) sum / numbers.length;
    }
}

// Called on the class, not an object
int m = MathUtils.max(10, 20);
double avg = MathUtils.average(80, 90, 85);

Rules for Static Methods

Can Access Cannot Access
Static variables Instance variables
Static methods Instance methods
Method parameters this keyword
class Employee {
    private String name;
    static int count;

    static void printCount() {
        System.out.println(count);    // OK — static variable
        // System.out.println(name);  // ERROR — instance variable
        // System.out.println(this);  // ERROR — no 'this' in static context
    }
}

Static Constants

static final fields are true constants — one copy, never changes:

class Constants {
    public static final double PI = 3.14159265358979;
    public static final int MAX_EMPLOYEES = 1000;
    public static final String COMPANY_NAME = "Acme Corp";
}

System.out.println(Constants.PI);
System.out.println(Constants.COMPANY_NAME);

Static Blocks

Run once when the class is first loaded:

class Config {
    static Map<String, String> settings;

    static {
        settings = new HashMap<>();
        settings.put("db.host", "localhost");
        settings.put("db.port", "5432");
        System.out.println("Config loaded!");
    }
}

Static vs Instance — When to Use Which

Use Static When Use Instance When
Utility methods (Math, Collections) Data varies per object
Constants (PI, MAX_SIZE) Behavior depends on object state
Factory methods Most methods
Counters shared across objects Default choice

Common static Examples in Java

Math.sqrt(25);           // static method
Integer.parseInt("42");  // static method
System.out.println();    // out is a static field of System
Collections.sort(list);  // static method

The main Method Is Static

public static void main(String[] args) { }

It’s static because Java needs to call it before any objects exist.


Quick Exercises

  1. Create a Student class that tracks total students created using a static variable.
  2. Write a StringUtils class with static methods isEmpty(), reverse(), capitalize().
  3. Why can’t a static method use this?

Summary

  • static variables: shared across all objects (one copy per class)
  • static methods: called on class, cannot access instance members
  • static final: constants
  • static { }: initialization block, runs once
  • Use static for utilities, constants, and shared state

What’s Next?

Let’s deep-dive into Constructors and Destructors — initialization, chaining, and cleanup.

Updated: