Skip to content

Static Class Members in Java

In Java, the static keyword is used to define class-level variables and methods that are shared among all instances of the class. These members belong to the class rather than any specific instance and can be accessed without creating an object.


Static Members

Static members include:

  1. Static Variables (Class Variables):
    1. Declared using the static keyword.
    1. Shared across all instances of the class.
    1. A single copy is maintained in memory.
  2. Static Methods:
    1. Declared using the static keyword.
    1. Can be called without creating an instance of the class.
    1. Cannot directly access non-static (instance) variables or methods.
  3. Static Blocks:
    1. Used to initialize static variables.
    1. Executes when the class is loaded into memory.

Static Variables

Features:

  • Declared at the class level with the static keyword.
  • Shared by all objects of the class.
  • Useful for defining constants or properties that are common to all objects.

Example:

class Counter {

    static int count = 0; // Static variable

    Counter() {

        count++; // Increment the static variable

    }

    static void displayCount() {

        System.out.println(“Count: ” + count);

    }

}

public class Main {

    public static void main(String[] args) {

        Counter c1 = new Counter();

        Counter c2 = new Counter();

        Counter c3 = new Counter();

        // Access static variable

        Counter.displayCount(); // Output: Count: 3

    }

}


Static Methods

Features:

  • Belong to the class rather than an instance.
  • Accessed using the class name (e.g., ClassName.methodName()).
  • Can only directly access static variables or other static methods.
  • Cannot use this or super keywords.

Example:

class MathUtils {

    // Static method

    static int add(int a, int b) {

        return a + b;

    }

}

public class Main {

    public static void main(String[] args) {

        // Call static method without creating an object

        int result = MathUtils.add(5, 10);

        System.out.println(“Result: ” + result); // Output: Result: 15

    }

}


Static Blocks

Features:

  • Used to perform class-level initialization.
  • Executes when the class is loaded into memory, before any objects are created or methods are called.
  • Can be multiple static blocks; they execute in the order they appear.

Example:

class Test {

    static int x;

    // Static block

    static {

        System.out.println(“Static block executed”);

        x = 10;

    }

}

public class Main {

    public static void main(String[] args) {

        System.out.println(“Value of x: ” + Test.x); // Output: Static block executed

                                                     //         Value of x: 10

    }

}


Static vs Non-Static Members

AspectStatic MembersNon-Static Members
Belongs ToClassObject
AccessClass name or instanceRequires an instance of the class
MemoryOne shared copy for all instancesSeparate copy for each instance
Direct AccessOnly static membersAll members
KeywordsCannot use this or superCan use this and super

When to Use Static Members

  • Static Variables:
    • To define constants (e.g., static final double PI = 3.14;).
    • To maintain a shared property across all instances (e.g., a counter or configuration setting).
  • Static Methods:
    • When functionality does not depend on instance-specific data.
    • For utility methods (e.g., Math.max(), Math.sqrt()).
  • Static Blocks:
    • To initialize complex static variables or configurations.

Example: Combining Static Members

class BankAccount {

    static double interestRate; // Static variable

    double balance; // Non-static variable

    static {

        // Static block to initialize static variable

        interestRate = 3.5;

    }

    BankAccount(double balance) {

        this.balance = balance;

    }

    // Static method to modify interest rate

    static void updateInterestRate(double newRate) {

        interestRate = newRate;

    }

    // Non-static method to calculate interest

    double calculateInterest() {

        return balance * (interestRate / 100);

    }

}

public class Main {

    public static void main(String[] args) {

        BankAccount acc1 = new BankAccount(1000);

        BankAccount acc2 = new BankAccount(2000);

        System.out.println(“Interest for acc1: ” + acc1.calculateInterest()); // Output: Interest for acc1: 35.0

        System.out.println(“Interest for acc2: ” + acc2.calculateInterest()); // Output: Interest for acc2: 70.0

        // Update interest rate

        BankAccount.updateInterestRate(4.0);

        System.out.println(“Interest for acc1: ” + acc1.calculateInterest()); // Output: Interest for acc1: 40.0

        System.out.println(“Interest for acc2: ” + acc2.calculateInterest()); // Output: Interest for acc2: 80.0

    }

}


Conclusion

Static class members in Java are powerful tools for sharing data and methods across all instances of a class. They are essential for creating constants, utility methods, and configurations at the class level. Understanding when and how to use static members is key to writing efficient and organized Java programs.