A Static method is declared with the static keyword. Making a static method in java required when you don’t want a create an object or method is not using any instance variable or method definition will not change or can’t be overridden. This is some reason when to use static methods in java.
It’s an interview question and many programmers can get confused to make a particular method static or not. The main advantage of the static method is you can call it without creating any class object. So if you want the direct call to a method, then make a static method.
Note: The main method in java itself is a static method.
When to use static methods in Java?
Define static methods in the following scenarios only:
- If writing utility classes and they are not supposed to be changed. ( e.g. java.lang.Math or StringUtils are good examples of classes, which use static methods).
- If the method is not using any instance variable.
- If any operation is not dependent on instance creation.
- If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
- When the definition of the method will never be changed or overridden. Static methods can not be overridden.
- Along with creational design patterns e.g. Factory and Singleton.
- A conversion tool e.g. valueOf()
Conditions make a method static in Java:-
Here is some condition when you can decide to make a static method. Based on our experiences, which helps to make a method static and also teaches when to use the static method in Java.
- If your method doesn’t modify the state of the object, or not using any instance variables.
- Call method without creating a class object.
- Creating Utility methods like- StringUtils.isEmpty(String text)
Example
public class Hello { public static void main(String args[]) { // calling static method without creating object. display(); } static void display() { System.out.println("Hello static method"); } }
Output: Hello static method
Restrictions for the static method
There are two main restrictions for the static method:-
- The static method can not use non-static data members or call the non-static method directly.
- this and super cannot be used in a static context.
Do comment if you have any doubts and suggestions on this tutorial.
Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java static methods in java codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.