static is a keyword in java applicable for variables, methods, and nested classes. A static method belongs to the class itself; hence it is also referred to as a class method. A static method cannot access non-static methods or variables of a class. Local variables cannot declare as static variables.
Static Method:
If a method declared with static, then it is called a static method. If any method is static, then no need to create an instance for that class to call the method. We can call the method with the class name without creating any references. In java, the main method is the best example of a static method.
public static void main(String args[]) { }
Example:
public class Test {
static void m1() {
System.out.println("Executed m1()");
}
public static void main(String[] args) {
m1();
}
}
Output:
Executed m1()
Static variable:
In java, static variables are class level variables means a single copy of the variable is created and shared among all objects.
Example:
public class Test {
static String str = "PLM Developer";
public static void main(String[] args) {
System.out.println("str value is= "+str);
}
}
Output:
str value is= PLM Developer
Static block:
Static block is executed only once at the time of class loading. If you want to perform any operations at the time of class loading like initialization of static variables, you can declare a static variable for that purpose.
Example:
public class Test {
static {
System.out.println("Inside static block");
}
static void m1() {
System.out.println("Executed m1()");
}
public static void main(String[] args) {
m1();
}
}
Output:
Inside static block
Executed m1()
0 Comments