Java Static Keyword
The static
keyword in Java is used to define class-level variables and methods. Class-level variables and methods belong to the class itself, rather than to individual instances of the class.
Here are a few key points about the usage of the static
keyword in Java:
Static Variables
A static variable is a variable that is shared among all instances of a class. It is declared using the static
keyword and is stored in the class rather than in individual objects. Here is an example:99
public class Counter {
private static int count = 0;
public Counter() {
count++;
}
public static int getCount() {
return count;
}
}
In this example, the count
variable is shared among all instances of the Counter
class and is incremented each time a new instance of the class is created.
Static Methods
A static method is a method that belongs to the class itself, rather than to individual instances of the class. It is declared using the static
keyword and is called using the name of the class rather than the name of an object. Here is an example:
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
In this example, the add
method is a static method that can be called using the following code:
int result = MathUtils.add(10, 20);
Static Initialization Blocks
A static initialization block is a block of code that is executed once when the class is loaded. It is used to initialize static variables or perform any other operations that need to be performed when the class is first loaded. Here is an example:
public class MyClass {
private static int[] numbers = new int[100];
static {
for (int i = 0; i < 100; i++) {
numbers[i] = i * i;
}
}
}
In this example, the static initialization block is used to populate the numbers
array with the squares of the numbers from 0 to 99.