Understanding Static vs Non-Static Methods in Java
Q: What is a static method in Java and how does it differ from a non-static method?
- Java
- Mid level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
In Java, a `static` method is a method that belongs to a class rather than to an instance of the class. This means that you can call a static method directly on the class itself, without having to create an instance of the class.
Here's an example of a static method:
public class MyClass { public static void myStaticMethod() { // code to be executed } }
To call this method, you can use the class name followed by the method name:
MyClass.myStaticMethod();
On the other hand, a non-static method is a method that belongs to an instance of the class. This means that you must create an instance of the class before you can call a non-static method.
Here's an example of a non-static method:
public class MyClass { public void myNonStaticMethod() { // code to be executed } }
To call this method, you must first create an instance of the class and then call the method on the instance:
MyClass myObject = new MyClass(); myObject.myNonStaticMethod();
The main difference between static and non-static methods is that static methods can be called directly on the class, while non-static methods can only be called on an instance of the class. Additionally, static methods cannot access non-static variables or methods of the class, while non-static methods can access both static and non-static variables and methods.
Static methods are often used for utility methods that perform a specific function that does not depend on the state of any particular instance of the class. Non-static methods are used for methods that depend on the state of a particular instance of the class, such as getter and setter methods.


