Java Static Keyword

Naveen AnamaneniUpdated · 5 min read

In a hostel, each room has its own fan and its own light, but the whole building shares one water tank and one notice board. Java classes work the same way. Ordinary fields belong to each object, like a room's fan. A static member belongs to the class itself: there's one copy, shared by every object, and it exists even when no object has been created yet.

One Shared Copy

Static: one per class. Instance: one per object
Bank.java▶ Try it
public class Bank {
    static class BankAccount {
        static String bankName = "PoolBank";
        static int totalAccounts = 0;
 
        String holder;
        long balance;
 
        BankAccount(String holder, long balance) {
            this.holder = holder;
            this.balance = balance;
            totalAccounts++;
        }
 
        static String branchCode(String city) {
            return city.substring(0, 3).toUpperCase() + "001";
        }
    }
 
    public static void main(String[] args) {
        System.out.println("Accounts before: " + BankAccount.totalAccounts);
        new BankAccount("Navika", 5000);
        new BankAccount("Srihitha", 12000);
        new BankAccount("Advitha", 800);
        System.out.println(BankAccount.bankName + " accounts: "
                + BankAccount.totalAccounts);
        System.out.println("Branch: " + BankAccount.branchCode("Pune"));
    }
}
Output
Accounts before: 0
PoolBank accounts: 3
Branch: PUN001

How it works

  1. Lines 3 and 4 are static variables: one bankName and one totalAccounts for the whole class.
  2. Line 21 reads totalAccounts before any object exists, through the class name.
  3. Each constructor call increases the same counter (line 12), so it ends at 3.
  4. Lines 15 to 17: a static method works only with its parameter and is called as BankAccount.branchCode(...).

Try it yourself: remove static from totalAccounts (line 4). What do the counts become, and why does line 21 stop compiling?

Where static Can Go

MemberEffectLesson
Static variableOne shared copy for the class"Instance Variable vs Static Variable"
Static methodCalled on the class; no this"Static Methods vs Instance Methods"
Static blockRuns once when the class is initialized"Static Block"
Static nested classA class inside a class that needs no outer object"Static Nested Class in Java"
Static importUse static members without the class name: import static java.lang.Math.PI;"Static Import in Java"

What Static Code Can't Do

Static methods and blocks run without an object, so they can't use instance fields, instance methods or this directly:

Compiler output
StaticCtx.java:1: error: non-static variable this cannot be referenced from a static context
public class StaticCtx { int count; static void inc() { this.count++; } }
                                                        ^

Instance methods, on the other hand, can use static members freely.

FromStatic membersInstance members
Static method or blockYesOnly through an object reference
Instance method or constructorYesYes

Common Mistakes

Making a per-object field static. A static balance would give every account the same balance.

Calling static members through an object. navika.totalAccounts compiles but misleads; write BankAccount.totalAccounts.

Making everything static to avoid "static context" errors. That throws away objects and their state. Create an object instead.

Interview Corner

What is the static keyword in Java?

static marks a member as belonging to the class rather than to any object. A static variable has one copy shared by all objects; a static method can be called without an object and can't use this or instance members directly; a static block runs once when the class is initialized; and a static nested class doesn't need an outer object.

Why is main static?

So the JVM can call it without creating an object of the class first. When the program starts, no objects exist yet.

Can a static method be overridden?

No. Static methods belong to the class and are chosen at compile time. A subclass can declare a static method with the same signature, but that hides the parent's method rather than overriding it (see "Can Static, Private and Final Methods Be Overridden").

Practice

  1. Easy: Add a static nextId to a Ticket class so each new ticket gets a unique number: 1, 2, 3...
  2. Harder: Write a class with a static method isValidPan(String pan) that checks a 10-character PAN format (5 letters, 4 digits, 1 letter) without creating any object.

Quick check: static

4 questions
1How many copies of a static variable exist?
2Can a static method read an instance field directly?
3How should you access a static variable count of class Ticket?
4Why is main static?

Key Takeaways

Was this tutorial helpful?

Lesson 105 of 482