In the previous article, we explored final variables and learned how initialization rules differ for instance, static, local variables, and method parameters.
In this article, we'll dive into one of the most important Java keywords:
static
The static keyword is frequently used in enterprise applications and is one of the most commonly asked topics in Java interviews.
Many beginners struggle with questions like:
- What is the difference between instance and static variables?
- Why is the
main()method static? - When should we use static methods?
- What is a static block?
- Can a class be declared static?
By the end of this guide, you'll have a solid understanding of the static keyword and know when to use it effectively.
What is the static Keyword?
The static keyword indicates that a member belongs to the class itself, rather than to individual objects.
It is applicable to:
- Variables
- Methods
- Blocks
- Nested (inner) classes
It is not applicable to:
- Top-level classes
- Constructors
- Local variables
| Applicable To | Allowed? |
|---|---|
| Variable | ✅ |
| Method | ✅ |
| Static Block | ✅ |
| Nested (Inner) Class | ✅ |
| Top-Level Class | ❌ |
| Constructor | ❌ |
| Local Variable | ❌ |
Why Do We Need static?
Imagine a banking application.
Every BankAccount object has its own balance.
However, all accounts belong to the same bank.
The bank name should be shared across every account.
Instead of storing the same value in every object, we store it once using static.
Example:
class BankAccount {
String accountHolder;
double balance;
static String bankName = "OpenAI Bank";
}
Now every object shares the same bankName.
Instance Variable vs Static Variable
Instance Variable
An instance variable belongs to an object.
Each object gets its own copy.
Example:
class Employee {
String employeeName;
}
Creating two objects:
Employee employeeOne = new Employee();
Employee employeeTwo = new Employee();
Memory:
Employee One
employeeName = "Rajesh"
Employee Two
employeeName = "Priya"
Each object stores its own value.
Static Variable
A static variable belongs to the class.
Only one copy exists regardless of the number of objects.
Example:
class Employee {
static String company = "OpenAI";
}
Memory:
Employee Class
company = "OpenAI"
▲
│
┌──────┴──────┐
│ │
Object 1 Object 2
Both objects use the same variable.
Practical Example
class Employee {
String employeeName;
static String company = "Tech Solutions";
Employee(String employeeName) {
this.employeeName = employeeName;
}
void display() {
System.out.println(employeeName + " works at " + company);
}
public static void main(String[] args) {
Employee employeeOne = new Employee("Rajesh");
Employee employeeTwo = new Employee("Priya");
employeeOne.display();
employeeTwo.display();
}
}
Output
Rajesh works at Tech Solutions
Priya works at Tech Solutions
Step-by-Step Explanation
Step 1
Each object gets its own employeeName.
Step 2
The company variable belongs to the class.
Step 3
Both objects share the same company.
Step 4
Changing the static variable affects every object.
Understanding Shared Static Variables
Consider the following example:
class Test {
int x = 10;
static int y = 20;
public static void main(String[] args) {
Test firstObject = new Test();
firstObject.x = 888;
firstObject.y = 999;
Test secondObject = new Test();
System.out.println(secondObject.x + "....." + secondObject.y);
}
}
Output
10.....999
Why?
-
xis an instance variable, so each object has its own copy. -
yis a static variable, so there is only one shared copy.
Memory:
firstObject
x = 888
│
│
▼
Static Area
y = 999
▲
│
secondObject
x = 10
Static Methods
A static method belongs to the class.
It can be called without creating an object.
Example:
class Calculator {
static int add(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
public static void main(String[] args) {
System.out.println(Calculator.add(10, 20));
}
}
Output
30
Why is main() Static?
The JVM starts program execution without creating an object.
Therefore, it needs a method that belongs to the class itself.
That's why the entry point is:
public static void main(String[] args)
Static Methods Can Access
Directly:
- Static variables
- Other static methods
Example:
class Demo {
static int count = 100;
static void display() {
System.out.println(count);
}
}
Static Methods Cannot Access Instance Members Directly
Incorrect:
class Demo {
int count = 100;
public static void main(String[] args) {
System.out.println(count);
}
}
Compile-Time Error
non-static variable count cannot be referenced from a static context
Why?
A static method executes before any object necessarily exists.
Without an object, there is no instance variable to access.
Correct:
class Demo {
int count = 100;
public static void main(String[] args) {
Demo demo = new Demo();
System.out.println(demo.count);
}
}
Static Blocks
A static block is executed once when the class is loaded into memory.
Example:
class DatabaseConfig {
static {
System.out.println("Loading database configuration...");
}
public static void main(String[] args) {
System.out.println("Application started");
}
}
Output
Loading database configuration...
Application started
Step-by-Step Explanation
Step 1
The JVM loads the class.
Step 2
The static block executes.
Step 3
The main() method runs.
When Are Static Blocks Useful?
Typical use cases include:
- Loading configuration files
- Initializing static variables
- Registering JDBC drivers (legacy code)
- Preparing application-wide resources
Static Nested Classes
A top-level class cannot be declared as static.
Incorrect:
static class Employee {
}
Compile-Time Error
modifier static not allowed here
However, a nested class can be static.
Example:
class Company {
static class Employee {
void display() {
System.out.println("Static Nested Class");
}
}
}
Static vs Instance Members
| Feature | Instance | Static |
|---|---|---|
| Belongs To | Object | Class |
| Number of Copies | One per object | One per class |
| Memory | Heap | Class (Method Area/Metaspace) |
| Access | Object reference | Class name (recommended) |
| Lifetime | Until object is eligible for GC | Until class is unloaded |
Common Beginner Mistakes
Mistake 1: Accessing Instance Variables from a Static Method
Incorrect:
System.out.println(balance);
Correct:
BankAccount account = new BankAccount();
System.out.println(account.balance);
Mistake 2: Using Objects to Access Static Members
Although this compiles:
employee.company = "Tech";
Prefer:
Employee.company = "Tech";
It clearly indicates that company belongs to the class.
Mistake 3: Declaring a Top-Level Class as Static
Incorrect:
static class Customer {
}
Only nested classes can be static.
Mistake 4: Overusing Static Variables
Avoid making every variable static.
If data belongs to an individual object, use instance variables.
Best Practices
- Use static variables for shared class-level data.
- Access static members using the class name, not object references.
- Keep static methods stateless whenever possible.
- Use static blocks only for complex initialization.
- Avoid global mutable static state unless absolutely necessary.
- Use meaningful names such as
companyName,totalEmployees, andapplicationVersion.
Interview Questions
1. What is the purpose of the static keyword?
It allows members to belong to the class rather than individual objects.
Why interviewers ask
To test your understanding of class-level memory.
2. Why is the main() method static?
The JVM calls it without creating an object.
3. Can a static method access instance variables directly?
No.
An object reference is required.
4. Can we overload static methods?
Yes.
Static methods can be overloaded.
5. Can static methods be overridden?
No.
They are hidden, not overridden.
6. Can constructors be static?
No.
Constructors initialize objects, while static members belong to the class.
7. Can a top-level class be static?
No.
Only nested classes can be declared static.
Quick Memory Trick 🧠
Remember SCOP:
S → Shared by all objects
C → Class member
O → One copy
P → Preferred access using Class Name
If you remember SCOP, you'll quickly recall the behavior of static members.
Key Takeaways
-
staticmembers belong to the class, not individual objects. - Static variables have only one shared copy.
- Static methods can be called without creating an object.
- Static methods can directly access only static members.
- Static blocks execute once when the class is loaded.
- Top-level classes cannot be static, but nested classes can.
- Use the class name to access static members for better readability.
- Understanding
staticis essential for Java interviews and enterprise development.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)