Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes To be static or not to be static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "To be static or not to be static" Watch "To be static or not to be static" New topic
Author

To be static or not to be static

Monmohan Singh
Ranch Hand

Joined: Aug 02, 2002
Posts: 82
Why and when should we declare methods as static in a class.
Are there any performance gains? and does it effect in multithreading environment
Natraj Gudla
Ranch Hand

Joined: Feb 09, 2003
Posts: 34
Methods are chosen to be declared as static when they perform some tasks,which are not specific to any particular object of the class.
as static methods belong to the class, they can be accessed by more than one thread at a time.and one has to be careful in programming. There is every chance that what ever content on which this methods works may be inconsistant.
Monmohan Singh
Ranch Hand

Joined: Aug 02, 2002
Posts: 82
but do they improve performance in any way?
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

Yes, they do. If you do not need an instance of an object to call the method, then why create the object? Object creation is inherantly an expensive task.
Secondly, static methods do no participate in overriding/polymorphism. There is no need to maintain/use a dynamic look-up table to determine which version of the method to call. In fact, the method to call is determined at compile-time by the compiler.
However, don't let performance guide you in a quest to make all methods static. Stick to good design, using static methods only as needed, and look for performance optimizations other places (DB access, Network I/O, etc).


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
Also keep in mind that static methods don't have access to any of the instance variables. So if you need manipulate instance variables you CAN'T use a static method. As Joel pointed out, the design should dictate the usage.
 
GeeCON Prague 2014
 
subject: To be static or not to be static