File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Method in java

 
sakthi moorthy
Ranch Hand
Posts: 54
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai to all my doubt is what is the purpose of the static method in java class when there is no main method like valueOf() method in String class
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you probably already know, a static method is one that can be invoked without having to first instantiate the containing class. In my experience, static methods are most often used for one of these two purposes:
  • Utility methods that provide some general functionality that's not specific to any one object. Example: Math.abs()
  • Factory methods to perform indirect instantiation of a class. Example: String.valueOf()

  • Some developers also use static methods as a substitute for the Singleton design pattern to enforce that only one "instance" of the class can ever exist at any given time. This is arguably a bad practice, however.
     
    Burkhard Hassel
    Ranch Hand
    Posts: 1274
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A static method is a method for a class, not for individual objects. It behaves the same for all individual objects. However it is allowed but not recommended (to avoid confusion) to call a static method on an object.
    The classical example of a static method (besides main ) is an object counter, e.g.

    The last two lines compile nicely but this is not recommended.

    Output:
    0
    2
    2
    2



    Yours,
    Bu.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic