A static
variable in Java is:
A class-level variable shared by all instances of that class.
It’s declared using the static
keyword inside a class but outside any method or constructor.
🔍 Syntax Example
public class Employee {
static int count = 0; // Shared by all Employee objects
public Employee() {
count++; // Increment every time a new Employee is created
}
}
In this example, no matter how many Employee
objects are created, count
belongs to the class, not to any single object.
🎯 Why Use Static Variables?
Purpose | Explanation |
---|---|
✅ Shared Values | Same value accessible to all instances of the class |
🧮 Memory Efficient | Only one copy exists in memory, not one per object |
💬 Access Without Object | Can access with ClassName.variableName |
🔁 Ideal for Counters, Constants | Great for tracking total objects, global flags, configs, etc. |
🧪 Real-World Example
public class BankAccount {
static String bankName = "SafeTrust Bank";
int accountNumber;
double balance;
// All accounts share the same bank name
}
All accounts created from BankAccount
share the same bankName
. You can change it globally with:
BankAccount.bankName = "NewSecure Bank";
🧠 Key Characteristics
- Belongs to the class, not object
- Loaded once when the class is loaded into memory
- Shared across all instances
- Can be accessed as
ClassName.variableName
- Often used with
static
methods
🚨 Common Mistakes (And Interview Gotchas)
Pitfall | What Happens |
---|---|
Declaring inside a method | ❌ Compile error—static is only allowed in class scope |
Forgetting it’s shared | Modifying it in one object affects all |
Using for per-instance data | Leads to incorrect or shared behavior |
✅ Final Interview Takeaways
- Use
static
when the variable’s value should be shared globally across all objects. - Think of it as a single copy sitting in memory, no matter how many objects you create.
- It’s excellent for counters, constants, configuration values, or utility class state.
- Pair it with
static
blocks orstatic methods
for consistent utility or logic encapsulation.