Let’s see some examples where use of java static methods are mandatory in the programs. Generally, we use static method where we want to call a method without creating an object of the class.
Here are examples where we cannot avoid using static methods in java and are indispensable.
NOTE: Generally, this question is asked to experienced candidate, but I have observed asking to freshers candidate too in technical interview.
Use of Static method in the main program.
Notice that the main () method is the starting point of the java programs and is static. So, the JVM can call the main () without creating an object of the class Sample.
public class Sample {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
A question may arise in your mind that what is problem with the JVM that it need only static main () method to start a program?
Reason is simple,
JVM looks for main () method in your program to execute as a starting point. Look at the above program, it has a Sample class and static main () method is inside that.
We know that to call a non-static method () of a class, first we need to create the object of the class and then can call it.
So, to call the method compiler need to create an object of the class if main () method is non-static. But, compiler look first main () method to start the program, only then it can create the object of the class. Hence, it is dead lock like situation.
If main () method is static, only then compiler can call it using class name without creating the object. This is the reason this method is Static.
NOTE: This interview question, why java main method is static, is a frequently asked question to freshers.
Use of java static method in Singleton class
We know that in singleton class design, we don’t allow user to create object of it and provide a static method to return an object/instance to make sure there is always only one instance of the class throughout the program life cycle.
Here is the snapshot of Singleton class where getInstance() method must be static to access from outside of class without creating an object. You can read complete example of singleton class in java.
class Singleton {
private static Singleton instance = null;
// Block user program / class to create object of this class
private Singleton() {
}
// Return object
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}