When to use static methods in Java?

Java Programming Java8Object Oriented Programming

You should use static methods whenever,

  • The code in the method is not dependent on instance creation and is not using any instance variable.
  • A particular piece of code is to be shared by all the instance methods.
  • The definition of the method should not be changed or overridden.
  • you are writing utility classes which should not be changed.


Live Demo

public class InstanceCounter {
   private static int numInstances = 0;
   protected static int getCount() {
      return numInstances;
   private static void addInstance() {
   InstanceCounter() {
   public static void main(String[] arguments) {
      System.out.println("Starting with "+InstanceCounter.getCount()+" instances");
      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      System.out.println("Created " + InstanceCounter.getCount() + " instances");


Started with 0 instances
Created 500 instances
Published on 23-Apr-2018 17:32:44