The static keyword in Java is used to indicate that a member (field, method, or inner class) belongs to a class rather than an instance of the class. This means that the member can be accessed without creating an instance of the class.
Here are some examples of how to use the static keyword in Java:
Static variable
A static variable is a variable that is shared among all instances of a class. It is defined with the static keyword and is typically initialized at the time of class loading.
public class MyClass {
// Static variable
private static int counter = 0;
// Constructor
public MyClass() {
// Increment the counter each time a new instance is created
counter++;
}
// Static method to get the current value of the counter
public static int getCounter() {
return counter;
}
}
In this example, the counter variable is a static variable that is shared among all instances of the MyClass class. The getCounter method is also static, which allows it to be called without creating an instance of the class.
Static block
A static block is a block of code that is executed when a class is loaded. It is defined with the static keyword and is typically used to initialize static variables.
public class MyClass {
// Static variable
private static int counter;
// Static block to initialize the counter
static {
counter = 10;
}
// Constructor
public MyClass() {
// Increment the counter each time a new instance is created
counter++;
}
// Static method to get the current value of the counter
public static int getCounter() {
return counter;
}
}
In this example, the static block is used to initialize the counter variable to the value 10. The static block is executed when the MyClass class is loaded, and the counter variable is initialized before any instances of the class are created.
Static method
A static method is a method that belongs to a class rather than an instance of the class. It is defined with the static keyword and can be called without creating an instance of the class.
public class MyClass {
// Static method to compute the factorial of a number
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
In this example, the factorial method is a static method that can be called without creating an instance of the MyClass class.
Static inner class
A static inner class is a class that is defined inside another class and is marked with the static keyword. It is similar to a regular inner class, but it does not have an enclosing instance.
public class MyClass {
// Static inner class
public static class InnerClass {
// Inner class method
public void printHello() {
System.out.println("Hello");
}
}
}
In this example, the InnerClass is a static inner class that can be accessed without creating an instance of the outer MyClass class.