Static and non-static variables and methods

Hi all,
There's an excellent thread that outlines very clearly the differences between static and non-static:
http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
My skeleton code then looks like this:
public class IMS extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        doPost(request, response);
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      //get the various parameters...
         if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
            if(action.equalsIgnoreCase("start"))
                try
                    IMSRequest imsRequest = new IMSRequest();
                    imsRequest.startIMS(response);
                catch(IOException ex)
                catch(ClassNotFoundException ex)
            else if(action.equalsIgnoreCase("stop"))
                try
                    StopIMS stopIMS = new StopIMS();
                    stopIMS.stop(response);
                catch(IOException ex)
             else if(action.equalsIgnoreCase("status"))
                try
                    ViewStatus status = new ViewStatus();
                    status.view(response);
                catch(IOException ex)
         else
            response.sendRedirect ("/IMS/wrongPassword.html");
public class IMSRequest
//a whole load of other variables   
  public  PrintWriter    out;
    public  int                 messageNumber;
    public  int                 n;
    public  boolean         status = false;  //surely this is a static variable?
    public  String            messageData = ""; // and perhaps this too?
    public IMSRequest()
    public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
        try
            response.setContentType("text/html");
            out = response.getWriter();
            for(n = 1 ; ; n++ )
                getMessageInstance();
                File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                if (n == 1 && file.exists())
                    file.delete();
                else if (file.exists())
                    throw new ServletException();
                try
                    databaseConnect();
               catch (ClassNotFoundException e)
//here I start to get compile problems, saying I can't access non-static methods from inside a static method               
               out.println(FrontPage.displayHeader()); 
                out.println("</BODY>\n</HTML>");
                out.close();
                Thread.sleep(1000);
        catch (Exception e)
    }OK, so, specifially, my problem is this:
Do I assume that when I instantiate the object imsRequest thus;
IMSRequest imsRequest = new IMSRequest();
imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
Damian

Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
If, however, from another class (FrontPage for
example), I call ((new.IMSRequest().writeHTML) or
something like that, then I'm creating a new instance
of IMSRequest (right?)That's what new does, yes.
and therefore I am never going
to see the information I need from my original
IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
On the other hand, IMSRequest is designed to run
continuously (prehaps for hours), so I don't really
want to just print out a continuous stream of stuff to
the browser. How can I though, every so often, call
the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

Similar Messages

  • Static variable and non-static

    I have a quick question. The following syntax compiles.
    private String t = key;
    private static String key = "key";
    But this doesn't compile.
    private String t = key;
    private String key = "key";
    Can anybody explain how it is treated in java compiler?
    Thanks.

    jverd wrote:
    doremifasollatido wrote:
    I understand that completely. I didn't say that the OP's version with static didn't work. I was just giving an alternative to show that you don't need static, if you change the order that the instance variables are declared.My problem with the underlined is that, while technically true, I can see where a newbie would take it as "oh, so that's how I can get rid of static," and focus only on how to satisfy the compiler, rather than on learning a) when it's appropriate to make something static or not from a design perspective, and b) what the implications of that decision are, for both static and non.
    I have just a wee bit of a prejudice against the "what do I type to make the error messages go away" approach. :-)That sounds good to me. We're currently trying to fix an issue caused by the fact that one class has most of its variables as static, when they should really be instance variables. There should only be one active instance of this class at a time, but the values of the static variables stick around when you call "new ThisClass()". So, old data interferes with new data, and various errors happen. The class has many static methods to access the static variables, but it should have been more of a Singleton--an actual object with non-static variables. The active instance of the Singleton would need to be replaced at logout/login (as opposed to shutdown completely and restart the JVM), but then at least when the new instance were created, then all of the variables would be initialized to empty--the old instance would disappear. The solution at the moment (solution by others--I don't agree) is to clear each static Vector and then set the reference to null (setting to null would be enough to drop the old data, but certain people don't get that...). This is fragile because many variables were missed in this "cleanup" process, and it will be easy to forget to "cleanup" new variables in the future. This class has been misdesigned for years (much longer than I've been here). The calls to static methods permeate the application, so it isn't easy to fix it quickly. There are several of these misdesigned classes in our application--a mix of static and non-static, when nothing or almost nothing should be static.

  • Abstract method versus static and non-static methods

    For my own curiosity, what is an abstract method as opposed to static or non-static method?
    Thanks

    >
    Following this logic, is this why the "public static
    void main" 0r "Main" method always has to be used
    before can application can be run: because it belongs
    to the class (class file)?
    Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
    RObin

  • Static Verse Non-Static Methods

    Let say I was going to write a class that contained
    methods to do the same thing as itoa() and atoi() functions
    in C. What would be the pros and cons of making those
    methods static verses non-static?

    Many thanks to all.
    In summary, (correct me if I am wrong or misunderstood)
    1) methods only needs to be instance methods if they use/access
    instance variables, otherwise class/static methods are preferred
    because then, one does not have to create an instance of the
    object and keep track it.
    2) relative to threads, a method only needs to be synchronized
    if it uses/accesses shared data.
    3) most likely, not very efficient to write wrappers for one
    liners like: Integer.parseInt(String s); etc.

  • Static Vs Non-static methods

    Hello,
    I wonder what should I use. I have got a class which does a lot of counting.. I can put the methods inside the class or make a class Math3D with the static methods that will count it.
    Which is the better way?

    BigDaddyLoveHandles wrote:
    deepak_1your.com wrote:
    Sorry mate... did not get that.By definition a utility class has all static methods. So as soon as you mention "utility class" you've already made a decision. The real question is "should method X be static or non-static"? My default position is to assume no method should be static, and then wait to be convinced.
    Look at utility class java.lang.Math, for example. It has static methods sin(), cos(), sqrt(), etc... An obvious choice for a utility class, right? Then they introduced class StrictMath in 1.3 with exactly the same static method signatures. That's a code smell that one should have written an interface and implemented it in at least two ways, but it's too late for that because the original methods are static.Good post.

  • Static vs Non static

    Hi,
    I was just not clear as to how does the compiler handle Static members.
    As far as fields are concerned if they are declared static, they are created on the HEAP and are shared by all the class instances.
    However, what i want to know is what happenes to the methods. I mean methods are just piece of code so why should a non-static method be instantiated for all the instances?
    So, I presume that static members mean that they are created on the HEAP.
    Am i right here?
    Thanks
    Praveen

    ... not clear as to how does the compiler handles Static members.
    As far as fields are concerned if they are declared
    static, they are created on the HEAP
    Not exactly.
    Methods live in the class definition which lives in Perm Space.
    and are shared by all the class instances.Yes.
    However, what i want to know is what happenes to the
    methods. I mean methods are just piece of codeSee above.
    so why should a non-static method be instantiated for all the instances?'tisn't.
    Methods are not instantiated.
    So, I presume that static members mean
    that they are created on the HEAP.
    Am i right here?No.
    I asked WHAT happens in the background in case of static methods.Why does it matter?
    I mean methods are just piece of code.
    So why this difference, wheather the method is
    static or non-static
    should not make any difference.The magic 'this' keyword can only be used in non-static methods.
    What i want to say is
    there should be some sort of store where the method's
    code is put and called irrespective of whether the
    method is static or non-static
    It is called Perm Space.

  • Static vs Non--Static members

    I'm having some trouble trying to understand the differences between static and non-static members.
    I've read a few online information about static members, but I don't understand the purpose of static members.
    Can someone try to explain the main points of static members and the differences between static and non-static members?

    I'm having some trouble trying to understand the
    differences between static and non-static members.
    I've read a few online information about static
    members, but I don't understand the purpose of static
    members.
    Can someone try to explain the main points of static
    members and the differences between static and
    non-static members?Static means only one per class. If you have a Class and generate 20 objects of this class or more, they all share the same copies of any static variables. This is as opposed to instance variables of which each Object has its own. If an object changes one of its instance variables, this doesn't affect another object's instance variables.
    Having said this, however, vague and general questions are great if you are face to face with a tutor where you can have a conversation but are very difficult to answer in this format. Your best bet is to go through several online articles (and there are many good ones, just google for them) and then coming back with specific questions. Another option is to go through a book or two. Most have a chapter covering this.
    Message was edited by:
    petes1234

  • Help with static and non static references

    Hi all,
    I'm new to Java I'm having some difficulties with accessing non static methods.
    I'm working with Tree data structures and all the interfaces and methods are non-static.
    I have to write a tester main method to create and modify trees but how do I access the non static fields from main which is static?
    Any help would be appreciated
    Thanks.

    Create an Instance for that particular class then call the method using that instance.

  • Problems with Static and non-static stuff

    Right now I am trying to work on a RPG and trying to make it all using classes instead of having a Applet run everything and want to call Methods to make / remove the buttons here is the Method I'm dealing with
        public void placeButtons()
            attackBtn.setBounds(200,700,75,25);
            defendBtn.setBounds(200,725,75,25);
            magicBtn.setBounds(275,700,75,25);
            itemBtn.setBounds(275,725,75,25);
            game.add(attackBtn);   // Here is where I am having the problem (non-static method add(java.awt.Component) cannot be referenced from a static context)
            attackBtn.addActionListener(this);
        }Normally I would be making all my buttons in my main class but I want to know if I can make them in a separate class and load them in my main class so I can shorten my code by a ton.

    Generally speaking: Yes: you are only limited by your ingenuity and knowledge.
    //call from other class
    MyButtonClass mbc = new MyButtonClass();
    MyPanel p = new MyPanel();
    p.add(mbc.getMyMainButton());
    //what everAlthough I would think that it may be better to get your entire Frame back for display or a panel... It just seems like it's going to be awkward to work with unless you're making some kind of button generator or something, but then it's your app and from your description, the code given should illustrate a way of getting to the answer you seek.

  • Mime Objects and non-static template

    Hi All,
    When I bring up a non-static web template, icons stored as mime objects are not initially displayed.  When I do a drill down or any other operation these are then displayed. 
    I know that this is not an issue with static layouts.
    Does anyone know how to force it so that these are displayed when the template is first called up?
    Cheers,
    Robert Zovic
    Arinso International

    Sorry Max,
    I originally included this in this group, although it is a web template designed using the Web Application Design tool.
    The template itself has had it's property set to non static.  This is to overcome issues with the connection/resources remaining locked by the ICM.
    The icons have been uploaded through se80.  It's strange but on the initial callup of the template they don't appear.  On each subsequent access, they do.
    Robert

  • Since the FF8 update, all bookmarks were lost and none of the recommended methods for restoring lost bookmarks work; I always get "Unable to process to backup file" even though the backup .json files still exist

    Since a FF8 update, all bookmarks were lost and none of the recommended restore methods work, even though I have been able to find the backup ".json" files; I continually get "Unable to process the backup file" for all methods of importing or restoring the bookmarks from the .json files. As others note, I can also no longer add any new bookmarks to my now empty bookmarks tab. My profile has not changed, so that's not the problem. This is really a pain.

    Did you try to delete the file places.sqlite to make Firefox rebuild the places.sqlite database file from a JSON backup?
    *http://kb.mozillazine.org/Unable_to_process_the_backup_file_-_Firefox
    A possible cause is a problem with the file places.sqlite that stores the bookmarks and the history.
    *http://kb.mozillazine.org/Bookmarks_history_and_toolbar_buttons_not_working_-_Firefox
    *https://support.mozilla.org/kb/Bookmarks+not+saved#w_places-database-file

  • Static vs. non-static errors!

    I dont understand why this doesn't work. Could someone explain the concept behind this error, and perhaps a solution, or another way of going about this?
    error:
    test.java:3: non-static method add(int,int) cannot be referenced from a static context
    add(1,2);
    ^
    1 error
    public class test {
       public static void main(String[] args) {
          add(1,2);
       public int add(int a, int b) {
          int c = a+b;
          return c;
    }

    You need to make your add() static:
    public static int add(int a, int b)
    Anything you reference in a static method - a method or a variable - that is defined ooutside of the static method must be defined as static. For example:
    public class test
    int x = 0;
    static int y =0;
    public static void main(String[] args)
    {      add(1,2); 
    System.out.println(x) // will cause an error - non-static variable referenced in static class
    System.out.println(y) // is okay
    public int add(int a, int b)
    {      int c = a+b;      return c;  
    }

  • Static to non-static

    Hello.
    I am trying a small die rolling program which pompts the user to enter the number of rolls in a specified range and print the frequency. Now, I want the results to be printed in a JTextArea but it doesn't work. I get cannot make a static reference to the non-static. If I use println() instead of setText(), it does print though.
    public static void main(String[] args){
              JFrame tFrame = new Roll();
              tFrame.setSize(600, 300);
              tFrame.setVisible(true);
              Random dice = new Random();
              int freq[] = new int[7];
              final int first = 1;
              final int limit = 10000;
         try{
              String enter = JOptionPane.showInputDialog(null, "Enter number of
                              rolls in range 1-10000");
              int range = Integer.parseInt(enter);
              if (range > limit){
                   JOptionPane.showMessageDialog(null, "You are not allowed
                             to enter an integer greater than 10000", "Error", JOptionPane.ERROR_MESSAGE);
                   System.exit(0);;
              if (range < first){
                   JOptionPane.showMessageDialog(null, "You cannot enter 0
                               or less than 1", "Error", JOptionPane.ERROR_MESSAGE);
                   System.exit(0);
              for(int i = 1; i < range+1; i++){
                   ++freq[1 + dice.nextInt(6)];
                   txt.setText("Result\tFrequency"); //<<<<cannot make a static reference
                   for (int result = 1; result < freq.length; result++){
                   txt.setText(result + "\t" + freq[result]);  //<<<<cannot make a static reference
              catch (final NumberFormatException nfe) {
                   JOptionPane.showMessageDialog(null, "Please
                              enter integer!", "Error", JOptionPane.ERROR_MESSAGE);
                   System.exit(0);
    }Help please?

    Whatever txt is: you can't call instance attributes or instance methods without actually having the instance first. That's what the compiler is trying to tell you.
    Consider having a main method like
    MyClass mc = new MyClass();
    mc.doStuff();In doStuff() you can then access all the non-static attributes and methods you defined.

  • Static calling non-static

    What is the best way aroung a static main method trying to call a non static method?

    Fixing the design of the program, IMHO. This kind of a
    think does not happen in a poperly designed program.Exactly. IF a static method needs to access a non-static variable, it needs to specify which instance of its class owns the variable.
    public static void main(Sting EAGLES[]))
       MyJDialog  mjd = new MyJDialog();
       mjd.setSomeParameter(true);
    }Here's the Reader's Digest Condensed Version&#169; of the rules (with grammatical license):
    1. A static method may only access the static data of it's class, not non-static data.
    2. static methods can only call static methods, not non-static.
    3. There ain't no this in static methods.
    4. You can't override a static method to be non-static.

  • Standard and Non-standard exports and queries issue

    Hi,
    We have created a few STANDARD books with standard exports in them. The standard exports use standard queries.
    The ISSUE is that in the Verifications/Filters tab, where we have put in a lot of queries - ONLY the STANDARD queries show up. We would like to have all the queries show up. I am the adminsitrator and still only the standard ones show up.
    I am worried that if I "Save As" the export as a non-standard export, it does not allow me to uncheck the standard tick column and save it but I have to manually change the name of the export. Can we change this in anyway?
    Is there a system preference where I can allow all the queries to show up in the verifications/filter tab at least for the admnistrators if not for all? Thanks
    - Ad

    Thanks for your input but DRM does seem to be behaving what you said or may be I am still missing something here.
    I created a standard query.
    I have a standard export.
    Now, in the verification/filter tab of my Standard export, I am able to see my standard queries.
    But,
    I am unable to see the Non-Standard Queries.
    HOWEVER,
    If I have a Non-Standard export --> I am able to ALL the queries. This makes it a lot more flexible in doing things.
    My question is the WHY are my standard exports not able to reach the non-standard queries. What I wanted to do a twist in my export for analysis purposes for a particular use. If non-standard exports have access to Standard and Non-Standard queries --> it just makes more sense to always use a non-standard export and create non-standard queries.

Maybe you are looking for

  • How do I select a new stationary or color for my emai

    I am writing an email via sbcglobal.net and I want to change the email page color to pink or I want to pick out flowers to be my new stationary. How do I do this. On classic there was a button that I would select and a drop down appeared giving me my

  • Generating outputfile on client machine.

    Hi. We all use various development tools such sqlplus, pl/sql developer, toad etc... some time (most of the time) user comes with adhoc requirement. so we write some code, (which we only know) and get the output. so we 'spool' and dbms_output to writ

  • SAP GRC 3.0 Custom workflow

    Hi, We are implementing GRC3.0 with portal intergration. The standard workflow appears to be working fine. I have a requirement of either customizing the standard workflow or creating a custom workflow to allow exceptions and remediation notification

  • Unit of Measure conversion in query runtime

    Hi all, I am attemoting to utilise the ability to convert key figure quantities in BI7, at query runtime by using a user entry variable and a conversion type. Does anybody know of any decent documentation as to how to configure this?  The SAP help do

  • Can any one tell me how to change the current row header in FB1LN tcode

    Hi, can any one tell me how to change the current row header in FB1LN tcode. I want to show input date also in the layout. Regards Mave