Java 'static' Keyword Tutorial
The static keyword in Java is used for memory management mainly.
We can apply java static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class rather than an instance of the class.
1. Java Static Variable
If you declare any variable as static, it is known as a static variable.
- The static variable can be used to refer to the common property of all objects (which is not unique for each object), e.g., the company name of employees, college name of students, etc.
- The static variable gets memory only once in the class area at the time of class loading.
public class Student {
int id;
String name;
static String college = "MIT"; // static variable
} 2. Java Static Method
If you apply static keyword with any method, it is known as static method.
- A static method belongs to the class rather than the object of a class.
- A static method can be invoked without the need for creating an instance of a class.
- A static method can access static data member and can change the value of it.
public class Calculate {
static int cube(int x) {
return x*x*x;
}
public static void main(String args[]){
int result = Calculate.cube(5);
System.out.println(result);
}
} 3. Java Static Block
Is used to initialize the static data member. It is executed before the main method at the time of classloading.
class A2 {
static { System.out.println("static block is invoked"); }
public static void main(String args[]) {
System.out.println("Hello main");
}
}