The static keyword in Java is used to indicate that a member (field or method) belongs to a class and not to an instance of the class. In other words, a static member is shared among all instances of a class and is not unique to any one instance.
One of the most common examples of the static keyword is using a static field. A static field is a field that is shared among all instances of a class and can be accessed without creating an instance of the class. For example:
class Counter {
static int count = 0;
int id;
Counter(){
count++;
id = count;
}
}
In this example, the count field is a static field and it’s shared among all instances of the Counter class.
Now, consider the following code:
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(c1.count); //Output : 2
System.out.println(c2.count); //Output : 2
Here, we create two instances of the Counter class, c1 and c2. Both instances share the same count field, which is incremented each time a new instance is created.
Another example of the static keyword is using a static method. A static method is a method that can be called without creating an instance of the class. For example:
class Calculator {
static int add(int x, int y) {
return x + y;
}
}
In this example, the add method is a static method and can be called without creating an instance of the Calculator class.
int result = Calculator.add(3,4);
System.out.println(result); //Output : 7
It’s worth noting that, a static method can only access static fields and call other static methods, it cannot access instance fields or call instance methods.
In summary,
- The static keyword in Java is used to indicate that a member (field or method) belongs to a class and not to an instance of the class.
- A static field is a field that is shared among all instances of a class and can be accessed without creating an instance of the class.
- A static method is a method that can be called without creating an instance of the class.
- A static method can only access static fields and call other static methods, it cannot access instance fields or call instance methods.
So, the static keyword is useful when you want to define a variable or method that is shared among all instances of a class, and does not depend on any specific instance.