0
0
JavaConceptBeginner · 3 min read

What is static keyword in Java: Explanation and Examples

In Java, the static keyword means a member (variable or method) belongs to the class itself, not to any specific object. This allows you to access it without creating an instance of the class.
⚙️

How It Works

Think of a class as a blueprint for making many houses (objects). Normally, each house has its own furniture (variables) and ways to do things (methods). But sometimes, you want something shared by all houses, like a streetlight that everyone sees. The static keyword marks such shared things.

When you declare a variable or method as static, it belongs to the class itself, not to any one object. This means you can use it directly through the class name without making a new object. It’s like having a common tool everyone can use instead of each house having its own copy.

💻

Example

This example shows a static variable and a static method. The static variable counts how many objects are created. The static method shows the count without needing an object.

java
public class Counter {
    static int count = 0; // shared by all objects

    public Counter() {
        count++; // increase count when new object is made
    }

    static void showCount() {
        System.out.println("Count is: " + count);
    }

    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter.showCount(); // call static method using class name
    }
}
Output
Count is: 2
🎯

When to Use

Use static when you want to share data or behavior across all objects of a class. For example:

  • Counting how many objects have been created.
  • Utility methods that don’t need object data, like math calculations.
  • Constants that never change, like static final values.

This saves memory and makes your code easier to manage because shared data lives in one place.

Key Points

  • Static members belong to the class, not objects.
  • You can access static variables and methods using the class name.
  • Static methods cannot use instance variables directly.
  • Static variables keep the same value for all objects.
  • Use static for shared data, constants, and utility methods.

Key Takeaways

The static keyword makes variables and methods belong to the class itself.
Static members can be accessed without creating an object.
Use static for shared data, constants, and utility functions.
Static methods cannot access instance variables directly.
Static variables keep a single shared value across all objects.