Static Fields and Methods

Introduction

Static members belong to the class rather than individual objects. They are shared among all instances of the class.


Static Fields

Static fields (class variables) are shared by all objects of the class.

Syntax:

static dataType fieldName;

Example:

class Student {
    static String schoolName = "ABC School";  // Static field (shared)
    String name;  // Instance field (per object)

    void display() {
        System.out.println("Name: " + name);
        System.out.println("School: " + schoolName);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "John";

        Student s2 = new Student();
        s2.name = "Alice";

        s1.display();
        s2.display();

        // Both share same schoolName
        System.out.println("School: " + Student.schoolName);
    }
}

Static Methods

Static methods belong to the class and can be called without creating an object.

Syntax:

static returnType methodName() {
    // code
}

Example:

class Calculator {
    // Static method
    static int add(int a, int b) {
        return a + b;
    }

    static int multiply(int a, int b) {
        return a * b;
    }
}

public class Main {
    public static void main(String[] args) {
        // Call without creating object
        int sum = Calculator.add(10, 20);
        int product = Calculator.multiply(5, 6);

        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);
    }
}

Static vs Instance

class Counter {
    static int staticCount = 0;   // Shared by all
    int instanceCount = 0;        // Per object

    Counter() {
        staticCount++;
        instanceCount++;
    }

    void display() {
        System.out.println("Static: " + staticCount);
        System.out.println("Instance: " + instanceCount);
    }
}

public class Main {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        c1.display();
        // Static: 1, Instance: 1

        Counter c2 = new Counter();
        c2.display();
        // Static: 2, Instance: 1

        Counter c3 = new Counter();
        c3.display();
        // Static: 3, Instance: 1
    }
}

Accessing Static Members

Access via Class Name (Preferred):

ClassName.staticField;
ClassName.staticMethod();
object.staticField;
object.staticMethod();

Example:

class Math {
    static final double PI = 3.14159;

    static double square(double n) {
        return n * n;
    }
}

public class Main {
    public static void main(String[] args) {
        // Preferred way
        System.out.println(Math.PI);
        System.out.println(Math.square(5));

        // Also works but not recommended
        Math m = new Math();
        System.out.println(m.PI);
        System.out.println(m.square(5));
    }
}

Static Method Rules

1. Cannot Access Instance Members:

class Example {
    int instanceVar = 10;
    static int staticVar = 20;

    static void staticMethod() {
        System.out.println(staticVar);     // ✓ OK
        // System.out.println(instanceVar); // ❌ Error
    }

    void instanceMethod() {
        System.out.println(instanceVar);   // ✓ OK
        System.out.println(staticVar);     // ✓ OK
    }
}

2. Cannot Use ‘this’ Keyword:

class Example {
    int value = 10;

    static void staticMethod() {
        // System.out.println(this.value);  // ❌ Error: no 'this' in static
    }

    void instanceMethod() {
        System.out.println(this.value);  // ✓ OK
    }
}

3. Can Only Call Static Methods:

class Example {
    static void method1() {
        method2();  // ✓ OK: both static
    }

    static void method2() {
        System.out.println("Static method");
    }

    void instanceMethod() {
        // Cannot call from static directly
    }
}

Common Use Cases

1. Utility Methods:

class StringUtils {
    static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    static String reverse(String str) {
        return new StringBuilder(str).reverse().toString();
    }
}

// Usage
if (StringUtils.isEmpty("   ")) {
    System.out.println("Empty string");
}

2. Constants:

class Constants {
    static final String APP_NAME = "MyApp";
    static final String VERSION = "1.0.0";
    static final int MAX_USERS = 1000;
}

// Usage
System.out.println(Constants.APP_NAME);

3. Counters:

class Employee {
    static int totalEmployees = 0;
    int empId;
    String name;

    Employee(String name) {
        this.name = name;
        this.empId = ++totalEmployees;
    }

    static int getCount() {
        return totalEmployees;
    }
}

// Usage
Employee e1 = new Employee("John");
Employee e2 = new Employee("Alice");
System.out.println("Total: " + Employee.getCount());  // 2

Complete Example

class Bank {
    static String bankName = "XYZ Bank";
    static int totalAccounts = 0;

    String accountNumber;
    String holderName;
    double balance;

    Bank(String holderName) {
        this.holderName = holderName;
        this.accountNumber = "ACC" + (++totalAccounts);
        this.balance = 0.0;
    }

    static void displayBankInfo() {
        System.out.println("Bank: " + bankName);
        System.out.println("Total Accounts: " + totalAccounts);
    }

    void displayAccountInfo() {
        System.out.println("Account: " + accountNumber);
        System.out.println("Holder: " + holderName);
        System.out.println("Balance: " + balance);
    }
}

public class Main {
    public static void main(String[] args) {
        Bank.displayBankInfo();

        Bank acc1 = new Bank("John");
        Bank acc2 = new Bank("Alice");
        Bank acc3 = new Bank("Bob");

        Bank.displayBankInfo();

        acc1.displayAccountInfo();
        acc2.displayAccountInfo();
        acc3.displayAccountInfo();
    }
}

main() Method is Static

public class Main {
    // main is static - called without creating object
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Why? JVM needs to call main() before any object is created.


Comparison Table

StaticInstance
Belongs to classBelongs to object
Shared by all objectsUnique per object
Access: ClassName.memberAccess: object.member
One copyMultiple copies
Cannot use thisCan use this
Cannot access instance membersCan access both
Memory allocated onceMemory per object

Memory Representation

class Student {
    static String school = "ABC";  // One copy in memory
    String name;                    // Copy per object
}

Student s1 = new Student();  // s1.name separate
Student s2 = new Student();  // s2.name separate
// Both share same 'school'

Memory:

Class Area:
  school = "ABC" (shared)

Heap:
  s1: { name = "John" }
  s2: { name = "Alice" }

Quick Reference

class Example {
    // Static field
    static int count = 0;

    // Instance field
    int id;

    // Static method
    static void staticMethod() {
        System.out.println(count);  // ✓ OK
        // System.out.println(id);  // ❌ Error
    }

    // Instance method
    void instanceMethod() {
        System.out.println(count);  // ✓ OK
        System.out.println(id);     // ✓ OK
    }
}

// Usage
Example.staticMethod();  // No object needed

Example obj = new Example();
obj.instanceMethod();    // Object needed

Exam Tips

Remember:

  1. static = belongs to class, not object
  2. Access using class name
  3. Shared by all objects
  4. Static methods cannot access instance members
  5. Cannot use this in static
  6. One copy in memory
  7. Useful for: utilities, constants, counters
  8. main() is static

Common Questions:

  • What is static keyword?
  • Difference between static and instance?
  • Can static method access instance variables?
  • Why is main() static?
  • How to access static members?
  • Use cases of static?
  • Can we use this in static method?