BCA / B.Tech 10 min read

The `static` Keyword in Java

What is the `static` Keyword in Java?

The static keyword indicates that a particular member (variable or method) belongs to the class itself, rather than to an instance (object) of that class. This means there is only one copy of a static member, which is shared among all objects created from that class. It is primarily used for memory management.

Analogy: Think of a `Student` class. An instance variable like `studentName` is unique to each student (each object). A static variable like `schoolName` would be common to all students, so it makes sense to store it once at the class level.


Uses of the `static` Keyword:
  • Static Variables (Class Variables): A single copy of the variable is created and shared among all objects of the class. It gets memory only once when the class is loaded.
    class Student {
        String name;
        static String schoolName = "Central University"; // Shared by all students
    }
  • Static Methods (Class Methods): A static method can be called directly using the class name, without needing to create an object. Static methods can only access other static members of the class directly. The `main` method is a prime example.
    class Calculator {
        static int add(int a, int b) { // Static method
            return a + b;
        }
    }
    // Calling the static method
    int sum = Calculator.add(5, 10);
  • Static Blocks: A block of code preceded by the `static` keyword. It is executed only once, when the class is first loaded into memory. It is used to initialize static variables.
    class MyClass {
        static {
            System.out.println("Static block executed.");
        }
    }