Difference between a static and a non static method in java.

Modified on Tue, 28 Mar, 2023 at 3:52 PM

In Java, a static method is a method that belongs to the class itself, rather than to any particular instance of the class. A non-static method, on the other hand, is a method that belongs to a particular instance of the class.


Here are some of the key differences between static and non-static methods in Java:


Invocation: A static method can be invoked on the class itself, while a non-static method can only be invoked on an instance of the class.


Access: A static method can only access static data members and other static methods of the class, while a non-static method can access both static and non-static data members and methods of the class.


Memory allocation: Static methods are allocated memory in the method area of the JVM, while non-static methods are allocated memory on the heap.


Polymorphism: Non-static methods can participate in polymorphism, as they can be overridden in subclasses, while static methods cannot be overridden.


Thread safety: Static methods are thread-safe by default, as they do not modify any state that is shared across instances of the class. Non-static methods, on the other hand, may not be thread-safe if they modify shared state.

Here is an example that illustrates the difference between static and non-static methods:

In this example, the incrementStaticCount() method is a static method that increments the staticCount variable, while the incrementInstanceCount() method is a non-static method that increments the instanceCount variable for a particular instance of the MyClass class. The main method creates two instances of the class and calls the two methods on them. When the program is run, it outputs the following:

This shows that the staticCount variable is shared across all instances of the class, while the instanceCount variable is specific to each instance of the class.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article