static Keyword

Static variables and methods

6 min read

static Keyword in Java

The static keyword means the member belongs to the class itself, not to any particular instance. Static members are shared across all objects.

Static Can Be Applied To

  • Variables: Class variables shared by all instances
  • Methods: Can be called without creating an object
  • Blocks: Executed once when class is loaded
  • Nested Classes: Inner class that doesn't need outer instance

🔑 Memory: Static members are stored in the Method Area (part of heap in modern JVMs), loaded once when class is loaded.

⚠️ Restriction: Static methods cannot access instance variables/methods directly. They need an object reference.

Code Examples

Static variables are shared across all instances

java
1// Static Variable (Class Variable)
2public class Counter {
3    // Static variable - shared by ALL instances
4    private static int count = 0;
5    
6    // Instance variable - unique to each object
7    private String name;
8    
9    public Counter(String name) {
10        this.name = name;
11        count++;  // Increment shared counter
12    }
13    
14    public static int getCount() {
15        return count;
16    }
17}
18
19// Usage
20Counter c1 = new Counter("First");
21Counter c2 = new Counter("Second");
22Counter c3 = new Counter("Third");
23
24System.out.println(Counter.getCount());  // 3 (shared count)
25
26// Static variable use cases
27public class MathConstants {
28    public static final double PI = 3.14159;
29    public static final double E = 2.71828;
30}
31
32double area = MathConstants.PI * radius * radius;

Static methods and their restrictions

java
1// Static Methods
2public class MathUtils {
3    // Static method - no object needed
4    public static int add(int a, int b) {
5        return a + b;
6    }
7    
8    public static int max(int a, int b) {
9        return a > b ? a : b;
10    }
11    
12    public static boolean isEven(int n) {
13        return n % 2 == 0;
14    }
15}
16
17// Call without creating object
18int sum = MathUtils.add(5, 3);      // 8
19int bigger = MathUtils.max(10, 7); // 10
20
21// Built-in static methods
22int abs = Math.abs(-10);           // 10
23double sqrt = Math.sqrt(16);       // 4.0
24String str = String.valueOf(42);   // "42"
25int parsed = Integer.parseInt("42"); // 42
26
27// Static method restrictions
28public class Example {
29    private int instanceVar = 10;
30    private static int staticVar = 20;
31    
32    public static void staticMethod() {
33        // System.out.println(instanceVar);  // ERROR!
34        System.out.println(staticVar);       // OK
35        
36        // Access instance through object
37        Example obj = new Example();
38        System.out.println(obj.instanceVar); // OK
39    }
40}

Static blocks for class initialization

java
1// Static Block - Initialization when class loads
2public class DatabaseConfig {
3    private static String url;
4    private static String username;
5    private static Connection connection;
6    
7    // Static block - runs once when class is loaded
8    static {
9        System.out.println("Loading config...");
10        url = "jdbc:mysql://localhost:3306/mydb";
11        username = "admin";
12        
13        try {
14            connection = DriverManager.getConnection(url, username, "password");
15        } catch (SQLException e) {
16            throw new RuntimeException("Failed to connect", e);
17        }
18    }
19    
20    public static Connection getConnection() {
21        return connection;
22    }
23}
24
25// Multiple static blocks execute in order
26public class MultiStatic {
27    static int value;
28    
29    static {
30        System.out.println("First block");
31        value = 10;
32    }
33    
34    static {
35        System.out.println("Second block");
36        value = value * 2;  // 20
37    }
38}

Singleton pattern and static import

java
1// Singleton Pattern - Common use of static
2public class Singleton {
3    // Static instance
4    private static Singleton instance;
5    
6    // Private constructor
7    private Singleton() {}
8    
9    // Static factory method
10    public static Singleton getInstance() {
11        if (instance == null) {
12            instance = new Singleton();
13        }
14        return instance;
15    }
16}
17
18// Thread-safe singleton (eager initialization)
19public class EagerSingleton {
20    private static final EagerSingleton INSTANCE = new EagerSingleton();
21    
22    private EagerSingleton() {}
23    
24    public static EagerSingleton getInstance() {
25        return INSTANCE;
26    }
27}
28
29// Static import - use static members without class name
30import static java.lang.Math.*;
31import static java.lang.System.out;
32
33public class StaticImportDemo {
34    public static void main(String[] args) {
35        out.println(sqrt(16));  // Instead of System.out, Math.sqrt
36        out.println(PI);        // Instead of Math.PI
37        out.println(max(5, 3)); // Instead of Math.max
38    }
39}

Use Cases

  • Utility/helper classes (Math, Collections)
  • Constants and configuration
  • Singleton pattern
  • Factory methods
  • Counters and shared state
  • Static initialization of resources

Common Mistakes to Avoid

  • Accessing instance members from static context
  • Overusing static (makes testing harder)
  • Thread safety issues with static variables
  • Static methods preventing polymorphism
  • Memory leaks from static collections
  • Confusing static with final