What is static method in Java Programming?

(Last Updated On: January 22, 2017)

Answer: Static method in Java programming is a method of a class that is preceded by static keyword. For example, static method is declared as below

//Static function

public static void LogError()

Static method belongs to a class not to the object. So, we can call static method of a class by using class name itself only without creating any object of the class in java code.

In below java program example , in the class Logger, LogError() method is a static method that will be called in main() program by using class name only.

 

However, static method can also be called by using an object of the class, but note that, it is not required as it is not the part of the object. However, Compiler will give a warning that static method can be accessed in static way if we call it using an object of the class. See the below java program example in which function has been called using an object of the class.

 

 

Note that a static method can access only java static variable data member and cannot access non static data member of the class. Static method  cannot access non static method also. In below example, if we remove the static keyword from data member errorCount, compiler will throw an error.

 

 

Generally, static method is used to create Utility kind of class where object creation of a class is not required and redundant. So, call all utility functions with class name by making them static methods in java.

Also, a frequently asked question that is, why main () method in Java is static?

 

This is by design. JVM is not required to create an object of a class to call main () method. Why it should go for extra memory allocation that is useless. So, make it static and call by class name only.

you can read another java interview question why main method is static in java