Examples where use of Java Static method is Indispensable

(Last Updated On: July 2, 2018)

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 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 main program.

Notice that the main () method the starting point of the java programs is static. So, the JVM can call the main () without creating an object of the class Sample.



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: Why java main method is static interview question is a frequently asked 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.