In Java, the static
keyword is used to create class-level variables and methods that are shared among all instances of a class. Static attributes and methods belong to the class itself rather than to any specific instance, making them useful for defining common data and behavior that should be shared across all instances of the class.
Static attributes (or static variables) are variables that are declared with the static
keyword. They are also known as class variables.
public class Counter {
// Static variable
private static int count = 0;
// Constructor
public Counter() {
count++;
}
// Static method to get the count
public static int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
// Output: 3
System.out.println("Number of instances: " + Counter.getCount());
}
}
In this example, the count
variable is static and shared among all instances of the Counter
class. Each time a new Counter
object is created, the count
is incremented. The static method getCount
is used to retrieve the current value of count
.
Static methods are methods that are declared with the static
keyword. They can be called on the class itself, without creating an instance of the class.
public class MathUtils {
// Static method
public static int add(int a, int b) {
return a + b;
}
// Static method
public static int subtract(int a, int b) {
return a - b;
}
}
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 3);
int difference = MathUtils.subtract(10, 4);
// Output: Sum: 8
System.out.println("Sum: " + sum);
// Output: Difference: 6
System.out.println("Difference: " + difference);
}
}
In this example, the add
and subtract
methods are static and can be called directly on the MathUtils
class without creating an instance.