What are Static variables?

Static variables or class variables are shared among all instances of a class and can be accessed and modified without creating an instance of the class. Let’s take a deep dive to understand the uses and implementation of static variables in Java.

Syntax and Restrictions of Static Variables in Java

When you declare a static variable in Java, the basic syntax looks like this:


        [access_modifier] static [data_type] variableName [= initialValue];

So, for example, you might write:


        public static int myStaticNumber = 42;

In this snippet: public is the access modifier (you could use private, protected, etc.) static indicates it’s a class-level (static) variable int is the data type myStaticNumber is the variable name = 42 sets the initial value (optional, but recommended to avoid default values)

That’s the essential pattern you’ll see whenever you declare a static variable in Java.

Where Can Static Variables Be Declared?

A big question is: “Where do static variables live?” The short answer is: directly in the class body, not inside methods or blocks. If you try to declare a static variable inside a method, you’ll get a compilation error, because static variables belong to the class itself, not to an instance or any local scope. Let’s see some examples.

Correct Declarations (in Class Body)


public class MyClass {
    public static String greeting = "Hello, World!";

    private static int count;

    static double pi = 3.14159;
    
    public static final int MY_CONSTANT = 100;

    public static void main(String[] args) {
        System.out.println(greeting);
    }
}

All of these declarations are in the class body, at the same level as main(). That’s exactly where static variables belong.

Incorrect Declarations (in Methods/Blocks)


public class MyClass {
    public static void main(String[] args) {
        static int invalidVar = 10;  // ❌ This won't compile!
    }
}

If you try declaring a static variable inside main() or any other method, Java will complain. Methods only allow local (non-static) variables. Remember: static variables are at the class level, not the instance or method level.

Why This Matters

Understanding where static variables can live is crucial because it affects how you structure your classes. Static variables are a single shared resource across all instances of a class—so placing them in methods just doesn’t make sense. By restricting them to the class body, Java keeps your code logical and avoids confusion about scoping.

Default Initialization of Static Variables

You might be wondering, “What happens if I don’t explicitly assign a value to my static variables?” Great question! In Java, static variables are automatically assigned default values when your class is loaded. That means you don’t have to worry about random garbage data floating around if you forget to give them an initial value.

So if you have a static integer you never set, Java initializes it to 0. A static boolean defaults to false, and object references default to null. This behavior is the same as for instance variables, but it’s good to remember that it applies to static variables too.

For example, if you declare:

public static int counter;

Java automatically sets counter to 0 behind the scenes, even if you never do something like counter = 10. This makes your code safer by preventing those weird uninitialized states that might appear in other languages.

Keep in mind that while default initialization is handy, it’s still best practice to assign meaningful initial values whenever possible—just to make your code more readable and intentional. But rest assured, if you skip it, Java’s got your back with those default values!

Static variable example in Java

One of the most common uses for static variables is to share among all instances of a class. For example, a counter variable that keeps track of the number of instances created, or a CONSTANT variable that holds a value that never changes. Consider a class that represents a bank account. The following code snippet shows how a static variable nextAccountNumber can be used to assign unique account numbers to each new account:

Example


// BankAccount class definition
class BankAccount {
  // Declare static variable nextAccountNumber 
  static int nextAccountNumber = 1001;

  // Declare instance variables for accountNumber and balance.
  int accountNumber;
  double balance;

  // BankAccount constructor that assigns unique account number to each instance
  BankAccount() {
    // Assign the current value of nextAccountNumber to accountNumber.
    accountNumber = nextAccountNumber;

    // Increment nextAccountNumber for the next BankAccount object.
    nextAccountNumber++;
  }

  // Method to get the account number of this BankAccount object.
  int getAccountNumber() {
    return accountNumber;
  }

  // Method to get the balance of this BankAccount object.
  double getBalance() {
    return balance;
  }

  // Method to deposit an amount into this BankAccount object.
  void deposit(double amount) {
    // Increase balance by the amount deposited.
    balance += amount;
  }

  // Method to withdraw an amount from this BankAccount object.
  void withdraw(double amount) {
    // Decrease balance by the amount withdrawn.
    balance -= amount;
  }
}

// Main method definition
class Main {
  static void main(String[] args) {
    // Create three BankAccount objects: account1, account2, and account3.
    BankAccount account1 = new BankAccount();
    BankAccount account2 = new BankAccount();
    BankAccount account3 = new BankAccount();
    
    // Display the value of the static variable nextAccountNumber after creating each BankAccount object.
    System.out.println("Value of nextAccountNumber after creating account1: " + account1.getAccountNumber());
    System.out.println("Value of nextAccountNumber after creating account2: " + account2.getAccountNumber());
    System.out.println("Value of nextAccountNumber after creating account3: " + account3.getAccountNumber());
  }
}

Output

Value of nextAccountNumber after creating account1: 1001 Value of nextAccountNumber after creating account2: 1002 Value of nextAccountNumber after creating account3: 1003
Static Variables in Java - 1In this example, the main method creates three instances of the BankAccount class. The BankAccount constructor assigns the nextAccountNumber to the new account and increments the nextAccountNumber variable by 1. The getAccountNumber method returns the account number of each account. The main method then prints out the account number and the nextAccountNumber variable for each account. You can see that each account number is unique and the nextAccountNumber variable is incremented by one for each new account created. Static variables can also be used to implement the Singleton design pattern, where only one instance of a class can be created. A singleton class is a class that can have only one instance in any Java application and simultaneously provides a global access point to this instance. The following code snippet shows how a static variable instance can be used to implement a singleton class:

Example


public class Singleton {
    // using static variable in the singleton class
    private static Singleton instance;
    private Singleton() { }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    public void displayMessage() {
        System.out.println("This is a singleton class");
    }

    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        singleton1.displayMessage();

        Singleton singleton2 = Singleton.getInstance();
        singleton2.displayMessage();

        Singleton singleton3 = Singleton.getInstance();
        singleton3.displayMessage();
    }
}

Output

This is a singleton class This is a singleton class This is a singleton class
In this example, the main method creates three instances of the Singleton class by calling the getInstance() method. The getInstance() method returns the instance of the class and creates a new instance if one does not exist. The displayMessage method just prints a message. Then the main method calls the displayMessage method for each instance. As you can see, even though we are creating three instances, only one object is created and shared among all the instances. It proves that only one instance of the class is created and shared among all the instances and the static variable 'instance' is holding. It's important to remember that the value of a static variable is shared among all instances of a class, so changes to the variable made by one instance will be visible to all other instances. Careful consideration should be given to static variables to avoid potential conflicts and bugs in your code. For example, using a static variable to hold a value that is specific to an instance of a class, such as an account balance, is not recommended. To reinforce what you learned, we suggest you watch a video lesson from our Java Course

Conclusion

To wrap this up, a static variable in Java allows sharing of data among all instances of a class. They can be used for variables shared among all instances, such as counters, and constants or to implement the Singleton design pattern. However, it's important to keep in mind that the value of a static variable is shared among all instances of a class, so changes to the variable made by one instance will be visible to all other instances.