Java Static Keyword

Master the static keyword to create class-level variables and methods that belong to the class itself, not to individual objects.

What is the Static Keyword?

The static keyword in Java is used to create members (variables and methods) that belong to the class itself rather than to any specific object. This means you can access static members without creating an object of the class.

Think of it this way: If you have 100 students in a class, each student has their own name and roll number (non-static). But the school name is the same for all students (static) - it belongs to the school itself, not to individual students.

Key Point: Static members are shared among all objects of a class. They are loaded into memory only once when the class is loaded, saving memory.

Types of Static Members

1. Static Variables

Static variables (also called class variables) are shared by all objects of the class. When one object changes a static variable, it affects all other objects.

Use Cases: Counter for total objects created, configuration settings, constants like company name

2. Static Methods

Static methods belong to the class and can be called without creating an object. They can only access static variables and other static methods directly.

Use Cases: Utility functions like Math.sqrt(), main() method, helper functions

3. Static Blocks

Static blocks are used to initialize static variables. They execute only once when the class is loaded into memory, before any object is created or static method is called.

Use Cases: Complex initialization of static variables, loading configuration files

Static Variable Example

Let's create a Student class where we count how many students have been created using a static counter variable.

Example: Counting Objects with Static Variable

class Student {
    String name;
    int rollNo;
    static int count = 0;  // Static variable shared by all students
    
    Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
        count++;  // Increment count when new student is created
    }
    
    void display() {
        System.out.println("Name: " + name + ", Roll No: " + rollNo);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Alice", 101);
        Student s2 = new Student("Bob", 102);
        Student s3 = new Student("Charlie", 103);
        
        System.out.println("Total Students: " + Student.count);
        
        s1.display();
        s2.display();
        s3.display();
    }
}
Output:
Total Students: 3
Name: Alice, Roll No: 101
Name: Bob, Roll No: 102
Name: Charlie, Roll No: 103

Explanation:

  • static int count = 0 - This variable is shared by all Student objects
  • Each time a Student object is created, count increases by 1
  • We access it using Student.count (class name, not object name)
  • All three students share the same count variable, so it shows 3

Static Method Example

Static methods can be called without creating an object. They're perfect for utility functions that don't need object-specific data.

Example: Calculator with Static Methods

class Calculator {
    // Static method to add two numbers
    static int add(int a, int b) {
        return a + b;
    }
    
    // Static method to multiply two numbers
    static int multiply(int a, int b) {
        return a * b;
    }
}

public class Main {
    public static void main(String[] args) {
        // Calling static methods without creating object
        int sum = Calculator.add(10, 20);
        int product = Calculator.multiply(5, 4);
        
        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);
    }
}
Output:
Sum: 30
Product: 20

Explanation:

  • We call Calculator.add() and Calculator.multiply() directly without creating a Calculator object
  • Static methods are memory-efficient for utility operations
  • The main() method is also static - that's why JVM can call it without creating an object

Static Block Example

Static blocks execute automatically when the class is loaded, even before the main method runs. Perfect for one-time initialization!

Example: Static Block Initialization

class Database {
    static String dbName;
    static int port;
    
    // Static block - runs once when class is loaded
    static {
        System.out.println("Static block executed!");
        dbName = "MyDatabase";
        port = 3306;
        System.out.println("Database initialized");
    }
    
    static void displayInfo() {
        System.out.println("Database: " + dbName);
        System.out.println("Port: " + port);
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Main method started");
        Database.displayInfo();
    }
}
Output:
Static block executed!
Database initialized
Main method started
Database: MyDatabase
Port: 3306

Explanation:

  • The static block runs first, even before main() method
  • It initializes the static variables dbName and port
  • Static blocks are useful for complex initialization that can't be done in a single line
  • A class can have multiple static blocks - they execute in order

Important Rules for Static

  • Static methods cannot use non-static members: They can't access instance variables or call non-static methods directly
  • Cannot use 'this' keyword: Since static methods don't belong to any object, 'this' has no meaning
  • Memory efficient: Static members are created only once and shared by all objects
  • Access using class name: Use ClassName.staticMember (though object.staticMember also works)

Common Mistake: Trying to access non-static variables from static methods will cause a compilation error. Always remember: static can only directly access static!

When to Use Static?

  • Constants: When you want to define constants shared across the class (e.g., PI, MAX_VALUE)
  • Utility Methods: For helper functions that don't need object data (e.g., Math.sqrt())
  • Counters: To track how many objects have been created
  • Shared Resources: Database connections, configuration settings
  • Factory Methods: Methods that create and return objects

Tip: If a variable or method doesn't need to be different for each object, make it static to save memory and improve performance!