Static keyword in Java
Static Keyword :
Introduction:
In Java, the static keyword is employed to declare class-level members (fields and methods) that are associated with the class itself rather than with individual objects. By using static, you can access these members directly using the class name without needing to create an instance of the class. As a result, static members are shared across all instances of the class, making them accessible and modifiable universally within the class context.
The static keyword is utilized in Java for the following:
1)variables
2)methods
3)block
4)nested class
static variable: static variable is a variable which is declared as static within a class, it becomes a class variable or a static variable.There will be only one copy of this variable that is shared by all instances of the class.static variables are initialized only once, at the start of the program execution, and they retain their values until the program terminates. Syntax: static dataType variableName;
static variable example:
class MyClass {
static int staticVar = 42;
}
static methods: static methods are methods which are declared as static it becomes a class method or a static method.static methods can be invoked using the class name without creating an instance of the class.They cannot access instance-level members (non-static variables or methods) directly since they don't have access to any specific instance.class MathUtils {
static int add(int a, int b) {
return a + b;
}
}
static block : A static block is a special block that is executed only once when the class is loaded into memory.It is used to perform any static initialization tasks or actions that need to be executed before the class is used.static {
// Static initialization code
}
static block example:
class MyClass {
static int staticVar;
static {
// This block will be executed only once during class loading
staticVar = 10;
}
}
class OuterClass {
// Static nested class
static class InnerClass {
// Class members and methods
}
}
Benifits of static keyword: