Why there should not be many static methods.

Why a java class should not have many static methods.How is memory managed in case of static methods.
If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.

shobhit123 wrote:
Why a java class should not have many static methods.How is memory managed in case of static methods.
If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.The reason to discourage static methods is stylistic rather than technical. It encourages object oriented thinking.
Each loaded class is represented by a Class object, and associated with that it a block of memory for static fields. As with all such storage this block is, as viewed from code, rather like an array with one, or in the case of double or long values, two slots per field.
Because the class loader maintains a map from FQN to Class this storage is only released if the class loader that loaded it becomes unreachable, which happens only in situations like the un-deployment of a web application or EJB.
Local variables for static methods are allocated in a stack frame, just as with instance methods. There's really no significant difference there.

Similar Messages

  • Why we should not declare a business method as final in EJBs - THX

    Why we should not declare a business method as final in EJBs - THX

    'cause it makes no sense at all and doesn't boost performance.
    regards
    dan
    scpj2

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • Why there is not an option to unable to 3G and use 2G on iPhone 4S ? It's awful! When will you fix that ?

    Why there is not an option to unable the 3G and use 2G on iPhone 4S ? It's awful! When will you fix that ? What are we gonna do now? I cant believe Apple can do it, like the battery of iPhone 4S is amazing. Everyday I should charge my phone! It doesnt make sense...

    YOu can't disable the camera - this feature came out with IOS 5.
    You will have to set your passcode lock to immediately.  settings - general - passcode lock.

  • I need adobe flash player for ipad ... Why there is not ????

    I need adobe flash player for ipad ... Why there is not ???? ... This is very important ???

    IOS device do not support Flash
    However Skyfire, Photon, iSwifter, Browse2Go and Puffin Web Browser will provide limited Flash capability

  • Why there is not unlock sound(IOS7)?

    Hi..I would like to know why there is not unlock sound..It was perfect and i would like it again!

    Yes, for some strange reason, the unlock sound was removed in iOS 7. While if I had to guess, it might be related to the use of Touch ID, that is a personal opinion and in no way reflects any great knowledge of anything in particular, just one of those, "I wonder why it does that" questions that kept me awake one night.

  • Why not to use static methods in interfaces?

    why?

    Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
    This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem.

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • Why we can not set oracle static parameters in memory

    Hi,
    I Know i am asking some impenetrable  question here But my intention  is to clear why still some parameter are static. there should be very strong reason behind that. anyone any idea. please somebody explain with any parameter why it is static.
    Warm Regards,
    Santosh Ganjure
    Mumbai
    Maharashtra(I)

    user13432927 wrote:
    Hi,
    One of my interview they asked me a question like we can use procedure using out parameters, why exactly need a function.
    I gave possible answers but they did not happy with them.
    Can you please tell me strong reason in practical way?
    Thanks
    kalpanaPossibly because the function needs to be called by SQL ... you can't use a procedure for that.

  • Why can't inner classes have static methods?

    I just tried to add a static method to an inner class, which would have been useful for extracting constants about said inner class, and it turns out that is not allowed.
    Of course I have other ways to code what I wanted, but I'm curious as to why this restriction was set in place. Anybody know?

    Probably because an inner class is tied to an instance of the enclosing class. I think that, conceptually at least, the inner class' definition itself only exists in the context of an instance of the enclosing class. While I'm sure it would have been technically possible to allow it, it would be confusing and not make a whole lot of sense--what is the static context for the inner class, since the class only exists in a non-static context?

  • I am not able access static methods from startup class

    I have a simple java class which queries the Database and holds some data. I am trying to access a static method of this class from the StartupClass and I am not able to do so. But I am able to access a static variable of the same class.
    Can someone help me here.

    Well, welcome to the world of "hacked" phones. If your purchase was from the US, you obviously purchased an iPhone that is locked to a US carrier. The iPhone must have been jailbroken and unlocked via software to accommodate your foreign SIM card. Now that you have updated the phone, it is locked back to the US carrier. Only the carrier can authorize Apple to unlock the iPhone and none of the US carriers will unlock the iPhones. Best suggestion is to sell the phone and obtain a factory unlocked version directly from the Apple store.
    To answer your other question, there is not a supported method to downgrade iOS.

  • Initializer block not called when static method called

    public class Initializer {
         Initializer(){
              System.out.println("Constructor called");
                   System.out.println("CLASS INITIALIZED");
         static void method(){
              System.out.println("Static method called");
         public static void main(String[] args) {
              Initializer.method();
    From the JLS
    A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
    T is a class and an instance of T is created.
    T is a class and a static method declared by T is invoked.
    [b]
    But when i call the static method , if the class is initialized shouldnt the initializer block be called, it is not called, why.

    Perhaps running something like this will add a little more colour?:
    public class Initializer {
        static {
            System.out.println("First static initializer");
            System.out.println("First instance initializer");
        Initializer() {
            System.out.println("Constructor");
        static {
            System.out.println("Second static initializer");
            System.out.println("Second instance initializer");
        static void staticMethod() {
            System.out.println("staticMethod");
        void instanceMethod() {
            System.out.println("instanceMethod");
        public static void main(String[] args) {
            System.out.println("main");
            staticMethod();
            new Initializer().instanceMethod();
    }

  • Too many static methods?

    Hello,
    I am using Oracle 9iAS 9.0.3. My app uses stateless session beans for data access.
    Does anyone have opinions about using static methods in ejb's, specifically there impact on performance under high load? Can a bottleneck be caused by a call to a static method by multiple beans?

    According to EJB Specification you cant declare your business methods static or final.
    --Venky                                                                                                                                                                                                   

  • Why there is not "security.enable_md5_signatures" option in some instllations of Firefox 28?

    In some instllations of Firefox 28 there is not "security.enable_md5_signatures" option.
    Where it is present, making it "true" not allow to be used md5 certificates like versions before 28.

    Thank you very much for useful explanation.
    Finally, from removing of "security.enable_md5_signatures" option, we must understand that MD5 certificates will not be supported from Firefox 28 and future versions, even option is set "true" in user set after updating the browser?
    We are familiar that from Firefox 16 there is no longer supporting MD5 as a hash algorithm in digital signatures, but if "security.enable_md5_signatures" option is set "true", browser works with them. May be this was changed [https://bugzilla.mozilla.org/show_bug.cgi?id=795398 here] and MD5 support is stopped?

  • I use Winamp and now the latest Firefox, is there any reason why I should not uninstal Internet explorer and windows media player, please advise.

    OS WinXP Home, service pack 3

    If I may, I see that you are using xp, but since its support is finished, for security reasons I advise you to go under windows 7 (if your pc allows).
    Well, I say that, but it's up to you :)
    It's the apprentice technician that is talking lol ;)

Maybe you are looking for

  • Pavilion g6 1378sa Hard drive not detected!!!

    Hi all,  Im new on the forum and really need hellp.   Let me explain: One day my notebook didnt start as normal...kept asking to repair the system,I have tried a few times and it still didnt fix the problem.I have 4 x 360 HDD spare ones at home so I

  • Images made into links (in divs) not working in Internet Explorer but works in Firefox. help!

    Hey guys, The text links are fine, but the image links don't work in internet explorer. Anyone know why this is happening? Sample code: <a href="facebook"><div class="fb"><img src="Facebook.png" /></div></a> The link links to another HTML in my site

  • Hide the Email notification in Email icon

    I configured 2 email Accounts in my ipad2 one for the Work. Another for the personal Account(Gmail) I like to hide the email notification for un-read mail from my personal account(Gmail) (Even if I fetch the data "Manually" from the advanced Option)

  • Compressor stops halfway - Computer wants to restart

    I have a mid-2006 17" Intel Core Duo iMac with Snow Leopard installed. I'm having problems with Compressor (3.0.5) being able to completely export a 2 and half hour video from Final Cut Pro. Like I said, the film I'm compressing is 2.5 hours of HD vi

  • Personnel Cost Planning PP2P

    In the transaction PP2P. When I try to add 10% to the basic salary of an employee, I want his Housing Allowance to be affect by that increas too. How can I set relations between the cost elements? Do I have to change in the ABAP code it self? regards