In Java, the “static” keyword is used to define class-level members that can be accessed without creating an instance of the class. It can be used with variables, methods, and inner classes.
Here are some common uses of the “static” keyword in Java:
Static variables: A static variable is a class-level variable that is shared by all instances of the class. It is declared using the “static” keyword before the data type. Static variables are used when you need to maintain a single copy of the variable across all instances of the class. For example, a static variable can be used to keep track of the number of objects created from a class.
public class MyClass {
static int count = 0;
public MyClass() {
count++;
}
}
In this example, the “count” variable is a static variable that is incremented every time an object of the class is created.
2. Static methods: A static method is a method that is associated with the class rather than with instances of the class. It is declared using the “static” keyword before the return type. Static methods can be called without creating an instance of the class, making them useful for utility methods that do not depend on instance variables.
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 takes two integers as arguments and returns their sum.
3. Static blocks: A static block is a block of code that is executed when the class is loaded into memory. It is declared using the “static” keyword followed by a pair of curly braces. Static blocks are useful for initializing static variables or performing other tasks that need to be done when the class is loaded.
public class MyClass {
static int count;
static {
count = 0;
// Other initialization code
}
}
In this example, the static block initializes the “count” variable to 0.
In summary, the “static” keyword in Java is used to define class-level members that can be accessed without creating an instance of the class. It is used with variables, methods, and inner classes.