DEV Community

Arun Kumar
Arun Kumar

Posted on

The static Keyword in Java

This post explores how static works with variables, methods, along with examples.

What is static Keyword?

The static keyword indicates that a particular member belongs to the class itself and not to instances of the class. That means:

  • Static variables and methods are shared among all instances.
    Static members can be accessed without creating object of class.

  • This makes static especially useful for scenarios where you want to store or manipulate common/shared data.

1. Static Variable (Class Variable)

A static variable is also known as a class variable. (which get memory each time an object is created), a static variable:

Gets memory only once at the time of class loading.
Is shared by all objects of the class.
Example Use Case:
collegeName for all students
companyName for all employees
Benefits:
Saves memory
Easy to maintain shared values

Class Employee {
    static String company = "ABC";
    int id;
    String name;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    void display() {
        System.out.println(id + " " + name + " " + company);
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Static Method

  • A static method:Belongs to the class, not to an object.

  • Can be called without creating an instances

  • Can only access static data members and static methods.
    When to Use:
    Factory methods

class Utility {
    static int cube(int x) {
        return x ;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)