In Java, the static
keyword is used to create variables and methods that are associated with a class rather than with individual objects of the class. This means that static
variables and methods can be accessed without creating an object of the class, using the class name instead.
Here’s an example of a static
variable:
public class Person {
private String name;
private static int count = 0;
public Person(String name) {
this.name = name;
count++;
}
public String getName() {
return name;
}
public static int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("John");
Person person2 = new Person("Mary");
Person person3 = new Person("Bob");
System.out.println(Person.getCount()); // output: 3
}
}
In this example, we have defined a Person
class with a static
variable called count
, which keeps track of the number of Person
objects that have been created. We have also defined a static
method called getCount
, which returns the value of the count
variable.
In the Person
constructor, we increment the count
variable every time a new Person
object is created. In the Main
class, we create three Person
objects and then use the getCount
method to retrieve the value of the count
variable.
static
methods can also be used to perform operations that are not specific to individual objects of the class. Here’s an example:
public class MathUtils {
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtils.factorial(5);
System.out.println(result); // output: 120
}
}
In this example, we have defined a MathUtils
class with a static
method called factorial
, which calculates the factorial of a given integer. We can call this method using the class name and the dot operator, without creating an object of the MathUtils
class.
In summary, the static
keyword is used in Java to create variables and methods that are associated with a class rather than with individual objects of the class. static
variables and methods can be accessed using the class name instead of an object reference.