In Java, the static keyword is used to indicate that a variable or method belongs to the class itself, rather than to individual instances of the class.
When applied to a variable, the static keyword indicates that the variable is a class variable, also known as a static variable. A class variable is shared by all instances of the class, and can be accessed directly using the class name. Here’s an example:
public class MyClass {
public static int count = 0;
public MyClass() {
count++;
}
}
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();
System.out.println(MyClass.count); // Output: 3
}
}
In this example, we define a class called MyClass that has a static variable called count. We also define a constructor for MyClass that increments the count variable each time a new instance of the class is created.
In the Main class, we create three instances of MyClass. Each time we create a new instance of MyClass, the count variable is incremented. Since count is a static variable, it is shared by all instances of the class, and we can access it using the class name. When we run this program, it outputs 3, which is the total number of instances of MyClass that have been created.
When applied to a method, the static keyword indicates that the method is a class method, also known as a static method. A class method belongs to the class itself, rather than to individual instances of the class. Here’s an example:
public class MyClass {
public static void doSomething() {
System.out.println("Doing something");
}
}
public class Main {
public static void main(String[] args) {
MyClass.doSomething();
}
}
In this example, we define a class called MyClass that has a static method called doSomething. We can call the doSomething method directly using the class name, without needing to create an instance of the class. When we run this program, it outputs Doing something.
In general, the static keyword is used to indicate that something belongs to the class itself, rather than to individual instances of the class. It is commonly used to define class variables and class methods. Note that static variables and methods can be accessed directly using the class name, without needing to create an instance of the class.