What is the static keyword in Java?

The static keyword in Java is used to make a variable, method, block, or nested class belong to the class itself rather than to individual objects. Because static members are associated with the class, they can be accessed without creating an object of that class.

Key Points: • Static members belong to the class, not to object instances. • A static variable is shared among all objects of the class. • Static methods can be called directly using the class name. • Static methods can access only static members directly. • Static members are loaded into memory only once when the class is loaded.

Example: Suppose a company has multiple employees. The company name is the same for all employees, so it can be declared as a static variable and shared by every object.

Code Example:

class Employee {

    static String companyName = "ABC Technologies";

    String employeeName;

    Employee(String employeeName) {
        this.employeeName = employeeName;
    }

    void display() {

        System.out.println(employeeName + " works at " + companyName);
    }
}

public class Demo {

    public static void main(String[] args) {

        Employee emp1 = new Employee("Amol");
        Employee emp2 = new Employee("Rahul");

        emp1.display();
        emp2.display();
    }
}

Output:

Amol works at ABC Technologies Rahul works at ABC Technologies

Common Uses of static:

1. Static Variables

• Shared among all objects • Memory-efficient because only one copy exists

Example:

static int count;

2. Static Methods

• Can be called without creating an object

Example:

class MathUtil {

    static int square(int num) {
        return num * num;
    }
}

MathUtil.square(5);

3. Static Blocks

• Used for class-level initialization • Executed only once when the class is loaded

Example:

static {
    System.out.println("Class Loaded");
}

Important Rules:

• Static methods cannot directly access non-static variables. • Static methods cannot use this or super keywords. • Static members are accessed using the class name whenever possible.

Example:

Employee.companyName

instead of

emp1.companyName

Benefits of static:

• Reduces memory usage • Provides shared data across objects • Allows utility methods without object creation • Supports class-level initialization

Interview Tip: A concise interview answer is:

"The static keyword makes a member belong to the class rather than to individual objects. Static variables are shared across all instances, and static methods can be called without creating an object. It is commonly used for constants, utility methods, counters, and class-level initialization."