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
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();
}
}
GO TO FULL VERSION