Advertisement
Google Ad Slot: content-top
Java Static Keyword
In Java, the static keyword is used for memory management and applies to variables, methods, and blocks. Anything declared static belongs to the class rather than any specific object.
Static Variables:
- Definition: A
staticvariable is shared among all objects of a class. It belongs to the class and is initialized only once, at the time of class loading. - Access: Can be accessed directly using the class name (
ClassName.variableName). - Use Case: To share common data between all objects.
Syntax:
class ClassName {
static DataType variableName;
}
Static Methods:
- Definition: A
staticmethod belongs to the class and does not require an object to be called. - Access: Can be called using the class name (
ClassName.methodName()).
Syntax:
class ClassName {
static ReturnType methodName(Parameters) {
// Method logic
}
}
Static Block:
- Definition: A
staticblock is used to initialize static variables or execute code during class loading. - Execution: Runs once, when the class is loaded into memory.
- Order: Static blocks execute before the
main()method or any static method.
Syntax:
class ClassName {
static {
// Static block logic
}
}