What is static keyword in Java: Explanation and Examples
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.
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 } }
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 finalvalues.
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.