In Java, a method is a block of code that performs a specific task. Methods can be either static or non-static.
A static method is a method that is associated with the class rather than with any particular instance of the class. This means that you can call a static method on the class itself, rather than on an object of the class. Static methods can access only static data members of the class and can not access instance variables.
A non-static method, also known as an instance method, is a method that is associated with a particular instance of a class. This means that you can only call a non-static method on an object of the class. Non-static methods can access both static and non-static data members of the class.
Hereβs an example Java program that demonstrates the difference between static and non-static methods:
public class MyClass {
private static int staticVariable = 0;
private int instanceVariable = 0;
public static void staticMethod() {
staticVariable++;
System.out.println("Static variable: " + staticVariable);
}
public void instanceMethod() {
instanceVariable++;
System.out.println("Instance variable: " + instanceVariable);
}
public static void main(String[] args) {
MyClass.staticMethod();
MyClass myObject1 = new MyClass();
myObject1.instanceMethod();
MyClass myObject2 = new MyClass();
myObject2.instanceMethod();
}
}
In this program, we define a class called MyClass that has a static method called staticMethod and a non-static method called instanceMethod. The staticMethod method increments a static variable and prints its value, while the instanceMethod method increments an instance variable and prints its value.
In the main method of the program, we call the staticMethod method on the MyClass class itself. We then create two objects of the MyClass class (myObject1 and myObject2) and call the instanceMethod method on each object. Note how the staticMethod method is called on the class, while the instanceMethod method is called on objects of the class.
When we run this program, it outputs the following:
Static variable: 1
Instance variable: 1
Instance variable: 1
This shows that the staticMethod method can be called on the class itself, while the instanceMethod method can only be called on objects of the class. Additionally, note how the static variable is incremented only once even though it was called twice while instance variables have incremented multiple times because they belong to each instance created.