1

what exactly is the use of java static methods? Yes i understand that they can be called without creating instance if in the same class. They can be called directly.

In case of main method, as it will be the first method to be called and has to be called without initializing it, static word justifies.

But in which other scenarios do we need to make a method static?

user2093576
  • 3,082
  • 7
  • 32
  • 43
  • 1
    to initialized class level data-structures when class loads – Grijesh Chauhan Jun 08 '13 at 06:47
  • 5
    This already has a lot of answers. See ***[this](http://stackoverflow.com/questions/2671496/java-when-to-use-static-methods)*** – Extreme Coders Jun 08 '13 at 06:48
  • There are infinite examples of static methods/classes. – Chris Dargis Jun 08 '13 at 06:50
  • Static methods are used for creating utilities that don't require object creation and thus are not dependent of object state. – Bhesh Gurung Jun 08 '13 at 06:51
  • read this: http://introcs.cs.princeton.edu/java/21function/ – Grijesh Chauhan Jun 08 '13 at 06:51
  • Some will certainly say *"to create utility methods in utility classes"*, but don't buy into that so fast. Singletons are still great here. Testable code, anyone? Static methods can, of course, be mocked, but how simple and natural is that? (ps.: this is not a reply to anyone, I'm just a slow typer...) – acdcjunior Jun 08 '13 at 06:52

3 Answers3

3

Simply If your method not related/depend on any of the instances they can better be static methods.

You points are on top and moreover,To avoid unnecessary object creation

An example from the java API is Math, all the variables and methods are static. Does it make sense to have to create a Math object just to call a single method.

Often people use this to write some Utility methods.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You gave the answer in your question: static methods are useful whenever you don't need an instance to do something. The typical example is:

public static int min(int a, int b);

This method just gives the min of two numbers and does not need a context (instance) to work.

Now you can use it as:

int min = YourClass.min(1, 2);

Had you declared it as an instance method, you would need to unnecessarily create a YourClass object.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

Static methods are used when you don't want to make an object of a class, such as in the Math class. If the math methods are static you don't have to create an object of the Math class. Other uses include for universal counter variables(making them static) and variables that everyone should know but are themselves are unable to be edited. Some more advanced uses include in threading and design patterns.

Sarah Szabo
  • 10,345
  • 9
  • 37
  • 60