0
0
JavaHow-ToBeginner · 3 min read

How to Use Static Variable in Java: Syntax and Examples

In Java, a static variable belongs to the class rather than any instance, meaning all objects share the same variable. You declare it using the static keyword inside a class but outside any method. This allows you to access the variable without creating an object of the class.
📐

Syntax

A static variable is declared inside a class with the static keyword. It is shared by all instances of the class and can be accessed using the class name.

  • static: keyword to declare the variable as static
  • type: data type of the variable (e.g., int, String)
  • variableName: name of the variable
java
class ClassName {
    static int variableName;
}
💻

Example

This example shows how a static variable is shared among all objects of a class. Changing it in one object affects all others.

java
class Counter {
    static int count = 0;

    void increment() {
        count++;
    }

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

public class Main {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();

        c1.increment();
        c1.display();  // Count: 1

        c2.increment();
        c2.display();  // Count: 2

        c1.display();  // Count: 2
    }
}
Output
Count: 1 Count: 2 Count: 2
⚠️

Common Pitfalls

Common mistakes when using static variables include:

  • Trying to access a static variable through an instance instead of the class name (though allowed, it is discouraged).
  • Modifying static variables unintentionally, causing unexpected shared state.
  • Confusing static variables with instance variables, leading to bugs.

Always remember static variables are shared across all objects.

java
class Example {
    static int value = 5;

    void changeValue(int newValue) {
        value = newValue;  // Changes shared static variable
    }
}

public class Test {
    public static void main(String[] args) {
        Example e1 = new Example();
        Example e2 = new Example();

        e1.changeValue(10);
        System.out.println(Example.value); // 10
        System.out.println(e2.value);     // 10 (shared)
    }
}
Output
10 10
📊

Quick Reference

  • Static variable: Shared by all instances of a class.
  • Access: Use ClassName.variableName to access.
  • Initialization: Can be initialized when declared or in static blocks.
  • Use case: For constants or counters shared across objects.

Key Takeaways

Static variables belong to the class and are shared by all instances.
Access static variables using the class name, not object references.
Changing a static variable affects all objects of that class.
Use static variables for shared data like counters or constants.
Avoid unintended changes to static variables to prevent bugs.