DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 3 - static Keyword: Variables, Methods, Blocks & Inner Classes

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";

}
Enter fullscreen mode Exit fullscreen mode

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;

}
Enter fullscreen mode Exit fullscreen mode

Creating two objects:

Employee employeeOne = new Employee();
Employee employeeTwo = new Employee();
Enter fullscreen mode Exit fullscreen mode

Memory:

Employee One
employeeName = "Rajesh"

Employee Two
employeeName = "Priya"
Enter fullscreen mode Exit fullscreen mode

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";

}
Enter fullscreen mode Exit fullscreen mode

Memory:

Employee Class

company = "OpenAI"

        ▲
        │
 ┌──────┴──────┐
 │             │
Object 1    Object 2
Enter fullscreen mode Exit fullscreen mode

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();
    }

}
Enter fullscreen mode Exit fullscreen mode

Output

Rajesh works at Tech Solutions
Priya works at Tech Solutions
Enter fullscreen mode Exit fullscreen mode

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);

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

10.....999
Enter fullscreen mode Exit fullscreen mode

Why?

  • x is an instance variable, so each object has its own copy.
  • y is a static variable, so there is only one shared copy.

Memory:

firstObject

x = 888
      │
      │
      ▼

Static Area

y = 999
      ▲
      │

secondObject

x = 10
Enter fullscreen mode Exit fullscreen mode

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));

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

30
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Static Methods Can Access

Directly:

  • Static variables
  • Other static methods

Example:

class Demo {

    static int count = 100;

    static void display() {

        System.out.println(count);

    }

}
Enter fullscreen mode Exit fullscreen mode

Static Methods Cannot Access Instance Members Directly

Incorrect:

class Demo {

    int count = 100;

    public static void main(String[] args) {

        System.out.println(count);

    }

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

non-static variable count cannot be referenced from a static context
Enter fullscreen mode Exit fullscreen mode

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);

    }

}
Enter fullscreen mode Exit fullscreen mode

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");

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

Loading database configuration...
Application started
Enter fullscreen mode Exit fullscreen mode

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 {

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

modifier static not allowed here
Enter fullscreen mode Exit fullscreen mode

However, a nested class can be static.

Example:

class Company {

    static class Employee {

        void display() {

            System.out.println("Static Nested Class");

        }

    }

}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Correct:

BankAccount account = new BankAccount();
System.out.println(account.balance);
Enter fullscreen mode Exit fullscreen mode

Mistake 2: Using Objects to Access Static Members

Although this compiles:

employee.company = "Tech";
Enter fullscreen mode Exit fullscreen mode

Prefer:

Employee.company = "Tech";
Enter fullscreen mode Exit fullscreen mode

It clearly indicates that company belongs to the class.


Mistake 3: Declaring a Top-Level Class as Static

Incorrect:

static class Customer {

}
Enter fullscreen mode Exit fullscreen mode

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, and applicationVersion.

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
Enter fullscreen mode Exit fullscreen mode

If you remember SCOP, you'll quickly recall the behavior of static members.


Key Takeaways

  • static members 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 static is 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)