File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes why do we use static methods? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why do we use static methods?" Watch "why do we use static methods?" New topic
Author

why do we use static methods?

krishna balaji
Ranch Hand

Joined: Mar 16, 2006
Posts: 31
i understood concept of static variables
can any one explain concept of static methods ?
why do we use static methods?
what all situations in which we can use static methods ?
why main is static?
where should we must use static and where satic methods should not be used?


Thanks
David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. An example from the java API is Math, all the variables are static. Does it make sense to have to create a Math object just to call a single method? Other then the fact that the methods perform some mathematical operation, there is little relation between them. In other words, there are no logical instance variables that would tie the math methods together. As an aside, you can't instantiate Math, so don't waste time trying.

A simple answer to why and when is 'whenever it makes sense". If a method needs to be in a class, but not tied to an object, then it makes sense. If the method is more logically part of an object, then it shouldn't be

Main is static because someone at Sun decided it would be better if the JVM could call main without creating an object first. It probably simplified the design of the JVM.


"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
where should we must use static and where static methods should not be used?


They are never really necessary. You could always do new Math().method() instead of Math.method().

There are some disadvantages. When you call one, you couple yourself directly to the class. It's impossible to use polymorphism and swap in another class later.

I've used them as a lazy shortcut (to avoid having to instantiate and object) and come to regret it several times. I stop and think hard before I add new static methods and especially classes with all static methods.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
Originally posted by Stan James:


They are never really necessary. You could always do new Math().method() instead of Math.method().

There are some disadvantages. When you call one, you couple yourself directly to the class. It's impossible to use polymorphism and swap in another class later.

I've used them as a lazy shortcut (to avoid having to instantiate and object) and come to regret it several times. I stop and think hard before I add new static methods and especially classes with all static methods.


You can instantiate Math?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by David McCombs:
... You can instantiate Math?

Correct me if I'm wrong, but I think that was a hypothetical example -- just to illustrate that static methods in Math could work much the same way if they weren't static and if Math could be instantiated.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Red Smith
Ranch Hand

Joined: Aug 05, 2007
Posts: 136
    
    1
Originally posted by krishna balaji:
i understood concept of static variables
can any one explain concept of static methods ?
why do we use static methods?
what all situations in which we can use static methods ?
why main is static?
where should we must use static and where satic methods should not be used?


Thanks


One use is when you want process data in a non-object-oriented way using what would be called "functions" in C and other languages. In addition to the Math class mentioned, there is the Arrays class (and probably others) that are just sets of C-style functions.
Shrikanth Nekkanti
Ranch Hand

Joined: Jul 12, 2007
Posts: 48
Hi krishna balaji

Let me clear your doubts
1.why do we use static methods?

To use a particular method in Java we first create a object to class which that method belongs to.Then by using object name.method name we call that method.

Example:
class Demo1
{
static dummyMethod1()
{
----------
-------
}
}

class Sample
{
public static void main()
{

//Use demo class method using classname.methodname
Demo1.dummyMethod1();

2.what all situations in which we can use static methods ?

The advantage of static method is we can use that method using classname.methodname without creating object to class to which it belongs.

Example:
class Demo
{
int dummyMethod()
{
----------
-------
}
}

class Sample
{
public static void main()
{
//create object to demo class
Demo obj=new Demo();

//Use demo class method using object
obj.dummyMethod();

3.why main is static?

To call a method in java we need an object.Program execution starts from main method we dont have a object to call main method in the begining.When JVM sees main method in program it starts execution from there.Since main method is static we can execute it without creating an object.


4.where should we must use static and where satic methods should not be used?

NOW YOU can answer this question i guess.
Red Smith
Ranch Hand

Joined: Aug 05, 2007
Posts: 136
    
    1
Oops, replied to my post when I was trying to edit it....
[ August 09, 2007: Message edited by: Red Smith ]
Gavin Tranter
Ranch Hand

Joined: Jan 01, 2007
Posts: 333
Dont you need static methods, when you wish to create objects using the Singleton pattern?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Oops, yes, Math was a bad example. Make that BistroMath.

I think there's going to be something static - methods or variables - to get the "global" access to a singleton. Would some other kind of registry work ... JNDI?
Red Smith
Ranch Hand

Joined: Aug 05, 2007
Posts: 136
    
    1
Originally posted by Gavin Tranter:
Dont you need static methods, when you wish to create objects using the Singleton pattern?


I found an example of a Singleton pattern in Java and they do make the constructor private to prevent normal instantiation and use a static to create one instance of the object:



http://www.javacoffeebreak.com/articles/designpatterns/index.html
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

The above Singleton patter is not thread safe.
Singletons are frequently overused, but that is a topic past a beginner's level.
tanuj pangtey
Greenhorn

Joined: Oct 19, 2007
Posts: 1
to save space in heap we use static, 'cause if you are not instantiating any class then it wouldn't make object in heap............
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39411
    
  28
Tanuj Pangtey, welcome to the Ranch.

I am not at all convinced about saving space in the heap. And people will by now have realised that it is impossible to instantiate the Math class!

I think there are two justifications for using static methods.

1: You do not have access to an instance of the class Examples
  • The main method has to be invoked before any objects are created at all.
  • The Singleton or similar getInstance() methods, even though the Singleton example given only works in a non-threaded application.
  • A method for retrieving an instance which has been serialised.

  • 2: When you neither use nor alter any of the object's state.
    You can have a method which takes parameters

    Caller--->information---->Method

    You can have a method without parameters

    Caller--->nothing-------->Method

    You can have a method with a return type

    Caller<----information<---Method

    You can have a method with a void return type

    Caller<---nothing<--------Method

    This is what all beginners are familiar with, but the method works the other way too

    Method--->information---->object state.

    That means it may alter the method state (changing the value of any fields)

    Method--->nothing-------->Object state.

    This method doesn't change any of the fields.

    Method<---information<----Object state.

    This method uses information from the fields in its workings.

    Method<---nothing<--------Object state

    This method doesn't use any information from any of the fields in its workings.

    Put them together

    Method<---nothing<--------Object state
    --->nothing-------->Object state.

    We now have a method which doesn't use the object state at all. Example:-
    Math.sin(). It takes a parameter, and calculates a result. But it doesn't need any access to any fields.
    Another example:-This takes all its information from the parameter, uses a formula and returns the answer. It doesn't do anything with the fields of the instance.

    So, any method which does not take any information from a field, and does not put any information into a field, does not have to be an instance method. Any method which does not use or alter any fields in its class or object might as well be a static method.
    Roger Chung-Wee
    Ranch Hand

    Joined: Sep 29, 2002
    Posts: 1683
    Another thing to consider is that you cannot override a static method because it is implicitly final. This makes JUnit testing difficult, so I would only use a static method which performs some small utility function and which I won't be JUnit testing.


    SCJP 1.4, SCWCD 1.3, SCBCD 1.3
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19720
        
      20

    Originally posted by Roger Chung-Wee:
    Another thing to consider is that you cannot override a static method because it is implicitly final.

    Not quite.

    You can "override" a non-final static method, although this is actually redefining it and hiding the original method; similar to redefining fields.
    If you mark a static method as final however, no subclass can define a static method with the same signature.


    SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
    How To Ask Questions How To Answer Questions
    Raghavan Muthu
    Ranch Hand

    Joined: Apr 20, 2006
    Posts: 3344

    Originally posted by Roger Chung-Wee:
    ....This makes JUnit testing difficult, so I would only use a static method which performs some small utility function and which I won't be JUnit testing.


    Isn't it way too much for a beginner's level and out of context as such?


    Everything has got its own deadline including one's EGO!
    [CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
    Raghavan Muthu
    Ranch Hand

    Joined: Apr 20, 2006
    Posts: 3344

    Krishna Balaji,

    As Campbell has clearly explained, i guess it would help you though. Just to summarise, if at all you want your method to make use of any of the instance values to perform its operation they should be instance level methods.

    On the other hand, if your method does NOT depend on any of the instances (and of course instances means values of instances), they can better be static methods. One advantage you get with the static methods is you don't need an object to call a static method, thereby you could save an object's memory there.

    In case of Math class, the way it is being fully static, there is absolutely no necessary to create/have an instance of it. Hope CR's explanation would better help you to get clarified with this.

    Math class serves the purpose of being a general purpose utility class which does NOT depend on any specific instance and its state
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: why do we use static methods?