What is static method in Java Programming?

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.

public class Logger {	
	
	//Static function
	public static void LogError(){
		
		System.out.println("Logging...");
	}	

}

public static void main(String[] args) {
				
		//static method call by class name only not object
		Logger.LogError();		
	}


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.

public static void main(String[] args) {
				
		//Create object and call static method
		//It will work but throw a warning
		Logger l = new Logger();
		l.LogError();
	}

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.

public class Logger {	
	
	private static int errorCount = 0;
	//Static function
	public static void LogError(){
		
		errorCount++;
		System.out.println("Logging Error..."+"Error count = "+errorCount );
	}	

}

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?

public class Test {

	public static void main(String[] args) {
		
	}
}

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.

Read another java interview question: Why main method is static in java?

Related Posts