Java Static Keyword
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
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"));
}
}Accounts before: 0
PoolBank accounts: 3
Branch: PUN001How it works
- Lines 3 and 4 are static variables: one
bankNameand onetotalAccountsfor the whole class. - Line 21 reads
totalAccountsbefore any object exists, through the class name. - Each constructor call increases the same counter (line 12), so it ends at 3.
- 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
| Member | Effect | Lesson |
|---|---|---|
| Static variable | One shared copy for the class | "Instance Variable vs Static Variable" |
| Static method | Called on the class; no this | "Static Methods vs Instance Methods" |
| Static block | Runs once when the class is initialized | "Static Block" |
| Static nested class | A class inside a class that needs no outer object | "Static Nested Class in Java" |
| Static import | Use 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:
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.
| From | Static members | Instance members |
|---|---|---|
| Static method or block | Yes | Only through an object reference |
| Instance method or constructor | Yes | Yes |
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
- Easy: Add a static
nextIdto aTicketclass so each new ticket gets a unique number: 1, 2, 3... - 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.
Key Takeaways
Was this tutorial helpful?