Explain the use of the static keyword in Java.
In Java, the static keyword is used to define methods, variables, blocks, or nested classes that belong to the class rather than any specific instance of the class. Here are its primary uses:
Static Variables:
A static variable is shared across all instances of the class.
It is initialized only once when the class is loaded.
public class Example {
static int count = 0; // shared among all objects
}
Static Methods:
These methods can be called without creating an instance of the class.
They can only access static variables or other static methods directly.
Static Blocks:
Used to initialize static data or perform setup tasks when the class is loaded.
Static Nested Classes:
A static nested class does not require an instance of the outer class.
The static keyword promotes memory efficiency and utility by enabling shared behavior across instances.