What is the static keyword in Java?
The static keyword binds a member to the class itself rather than to an instance — so it lives in one place and is shared across all objects.
Static variable — one shared copy per class; commonly used for constants (
public static final).Static method — called on the class without an instance; cannot use
thisor instance fields.Static block — runs once when the class is loaded; used to initialize static fields.
Static nested class — a nested class that does not capture an enclosing instance.
Use cases — constants, utility classes (
Math,Collections), factory methods, singletons.
public class DatabasePool {
private static DatabasePool instance; // Static variable
private static final int MAX_CONNECTIONS = 10; // Static constant
private static int connectionCount = 0; // Shared counter
static { // Static block
System.out.println("Pool class loaded");
// Complex initialization
}
private DatabasePool() {} // Private constructor
public static DatabasePool getInstance() { // Static method
if (instance == null) {
instance = new DatabasePool();
}
return instance;
}
public Connection getConnection() {
connectionCount++; // Shared across all users
return createConnection();
}
public static int getConnectionCount() {
return connectionCount;
}
}instance and connectionCount are shared across all code using DatabasePool. getInstance() is a static factory method (Singleton pattern). The static block runs once when the class loads.
MAX_CONNECTIONS is a static constant. connectionCount tracks total connections across the application.
Know all five uses: variables, methods, blocks, inner classes, and imports. The key rule: static methods cannot access instance members.
Mention that static methods are not polymorphic (hidden, not overridden). The Singleton example connects to design patterns.