Static Variable in Java

Static Variable in Java: A Comprehensive Guide

In Java, the static keyword is used to define class-level variables, methods, and blocks. When applied to a variable, it makes the variable shared among all instances of the class. Understanding static variables is crucial for efficient memory management and creating programs where shared data is needed.

In this tutorial, we’ll focus on static variables, explaining what they are, how they work, and how to use them effectively.


What is a Static Variable?

A static variable in Java is a variable that belongs to the class rather than instances (objects) of the class. This means that all objects of the class share the same static variable. When a variable is declared as static, a single copy of that variable is created and shared among all instances of the class.

Syntax:

class ClassName {
    static dataType variableName;
}

Characteristics of Static Variables

  1. Shared Among All Instances: A static variable is shared by all objects of the class. Any changes made to the variable are reflected across all instances.

  2. Class-Level Scope: Static variables belong to the class itself and not to any specific object. They are initialized when the class is first loaded into memory.

  3. Memory Efficiency: Since static variables are shared, they help reduce memory usage as only one copy of the variable exists, regardless of the number of instances.

  4. Accessed Using Class Name: Although static variables can be accessed through objects, the recommended way is to access them using the class name.


Example of a Static Variable

Let’s start with a simple example to demonstrate how static variables work.

class Counter {
    static int count = 0; // Static variable

    Counter() {
        count++; // Increment static variable
        System.out.println("Count: " + count);
    }
}

public class StaticVariableExample {
    public static void main(String[] args) {
        // Creating objects
        Counter obj1 = new Counter();
        Counter obj2 = new Counter();
        Counter obj3 = new Counter();
    }
}

Output:

Count: 1
Count: 2
Count: 3

Explanation:

  • The count variable is declared as static, so it is shared among all instances of the Counter class.

  • Each time a new Counter object is created, the static count variable is incremented. The value of count is shared, so it reflects the total number of objects created.


Accessing Static Variables

Static variables can be accessed in two ways:

  1. Using the Class Name: This is the recommended way to access static variables.

    ClassName.variableName;
  2. Using an Object: Although possible, this is not recommended as it can be misleading.

    objectName.variableName;

Example:

class MyClass {
    static int staticVar = 10;
}

public class AccessStaticVariable {
    public static void main(String[] args) {
        // Accessing static variable using class name
        System.out.println("Static Variable: " + MyClass.staticVar);

        // Accessing static variable using an object (not recommended)
        MyClass obj = new MyClass();
        System.out.println("Static Variable: " + obj.staticVar);
    }
}

Output:

Static Variable: 10
Static Variable: 10

Static Variables vs Instance Variables

  1. Static Variables:

    • Belong to the class.

    • Shared among all instances.

    • Initialized when the class is loaded.

    • Accessed using the class name.

  2. Instance Variables:

    • Belong to individual objects.

    • Each object has its own copy.

    • Initialized when the object is created.

    • Accessed using object references.

Example:

class MyClass {
    static int staticVar = 10; // Static variable
    int instanceVar = 20; // Instance variable
}

public class StaticVsInstance {
    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();

        // Accessing static variable
        System.out.println("Static Variable (obj1): " + obj1.staticVar);
        System.out.println("Static Variable (obj2): " + obj2.staticVar);

        // Accessing instance variable
        System.out.println("Instance Variable (obj1): " + obj1.instanceVar);
        System.out.println("Instance Variable (obj2): " + obj2.instanceVar);

        // Modifying static variable using obj1
        obj1.staticVar = 100;

        // Modifying instance variable using obj1
        obj1.instanceVar = 200;

        System.out.println("After Modification:");
        System.out.println("Static Variable (obj1): " + obj1.staticVar);
        System.out.println("Static Variable (obj2): " + obj2.staticVar);
        System.out.println("Instance Variable (obj1): " + obj1.instanceVar);
        System.out.println("Instance Variable (obj2): " + obj2.instanceVar);
    }
}

Output:

Static Variable (obj1): 10
Static Variable (obj2): 10
Instance Variable (obj1): 20
Instance Variable (obj2): 20
After Modification:
Static Variable (obj1): 100
Static Variable (obj2): 100
Instance Variable (obj1): 200
Instance Variable (obj2): 20

Explanation:

  • The static variable staticVar is shared between obj1 and obj2. Changing it through obj1 also changes it for obj2.

  • The instance variable instanceVar is separate for each object. Changing it for obj1 does not affect obj2.


When to Use Static Variables

  1. Shared Data: When you need a variable that is shared across all instances of a class, such as a counter that tracks the number of objects created.

  2. Constants: Static variables are often used for constants, where a single value is shared and does not change throughout the program.

  3. Utility Classes: In utility classes where you need to store common data that should not be tied to any particular instance.


Advantages of Static Variables

  1. Memory Efficiency: Only one copy of the static variable is created, regardless of how many instances of the class are created.

  2. Shared Data: Static variables are ideal for storing data that needs to be shared across all instances of a class.

Disadvantages of Static Variables

  1. Lack of Flexibility: Since static variables are shared, they lack the flexibility of instance variables, which are unique to each object.

  2. Tight Coupling: Overusing static variables can lead to tightly coupled code, making it harder to modify and maintain.


Conclusion

Static variables in Java are a powerful feature that allows you to create variables shared across all instances of a class. They are particularly useful for constants, counters, and shared data. However, they should be used judiciously to avoid tight coupling and maintain flexibility in your code.

For more Java tutorials and resources, visit codeswithpankaj.com.

Last updated