Java Static Variables, Methods, and Classes
Master Java Static Concepts: Learn static variables, static methods, static classes, static initialization blocks, memory management, utility patterns, and real-world examples.
1. Introduction to static
The static keyword belongs to the class itself rather than any instance. Static members are shared across all objects of the class.
- One copy per class, not per object
- Access via ClassName.member
- Static methods cannot use this
- Loaded when class is first used
class Counter {
static int count = 0;
Counter() { count++; }
static int getCount() { return count; }
}
2. Static Variables
Static variables (class variables) store shared state such as counters, configuration flags, or cached constants used by all instances.
- Declared with static keyword
- Initialized when class loads
- Shared by all instances
- Access with class name preferred
class AppConfig {
static String appName = "LearnHub";
static int maxUsers = 100;
}
public class StaticVarDemo {
public static void main(String[] args) {
System.out.println(AppConfig.appName);
}
}
3. Static Methods
Static methods belong to the class. Utility methods like Math.max and main are static because they do not need object state.
- Cannot access non-static members directly
- Call without creating object
- Common in utility classes
- Use static import sparingly
class MathUtil {
static int square(int n) { return n * n; }
}
public class StaticMethodDemo {
public static void main(String[] args) {
System.out.println(MathUtil.square(6));
}
}
4. Static Nested Classes
A static nested class is a static member class. It behaves like a normal class nested for packaging convenience and does not require an outer instance.
- Declared static inside outer class
- Can have static members
- Used in builder pattern
- Outer class name as namespace
class Database {
static class Connection {
void connect() { System.out.println("Connected"); }
}
}
public class NestedStaticDemo {
public static void main(String[] args) {
new Database.Connection().connect();
}
}
5. Static Initialization Blocks
Static blocks run once when the class is loaded. Use them for complex static field initialization that cannot fit on one line.
- Runs before any static method or constructor
- Multiple blocks run in declaration order
- Can throw exceptions in static context
- Alternative to static factory setup
class Loader {
static int value;
static {
value = 42;
System.out.println("Class loaded");
}
}
6. Static Best Practices
Use static for true class-level behavior. Overusing static makes testing harder and hides dependencies.
- Avoid static mutable global state
- Use static for utility methods
- Do not make everything static
- Initialize constants as static final
- Prefer dependency injection over static in apps