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;  
}

Similar Messages

  • 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 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 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 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

  • 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.

  • 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.

  • 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.

  • 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.

  • Static vs non static methods - best practice

    I have a question with regards to program design.
    If I have a class that looks something like:
    public class SampleApp extends Engine implements Listener_OnMyEvent
    public static void main(String argv[])
    int x=10;
    //Call metod1
    Method1(x);
    public method1(int i)
    //Call a method from the Engine Class
    //I know I don't have to have "Engine." here but it's just to
    clearify
    Engine.method2();
    public void OnMyEvent()
    Log("Event Hapended");
    Let's say now that I want to move method1 to another class/file in
    order to keep the code as neat and tidy as possible.
    How should I do that? What is best practice according to you? Should
    the methods there be static?
    I tried to create:
    public class MyMethods
    public static method1(int i)
    Engine.method2();
    ...but then method2 isn't available since Engine isn't implemented
    unless I pass the whole class along:
    MyMethods(x, this)
    Is this correct?
    I hope you see what I'm getting at here.
    Any suggestions is appreciated.
    Thanks

    Then you would have a cyclic dependency which suggests a design error.
    But other than that you just pass an instance of the first class when your construct the second one.

  • Static or non-static...

    Well i guess this is a design issue...
    If i make an application, and create a main object for it like "App".
    Now i want the application to have some internal code for like maybe a network, and call it "Net".
    Now in the App, should i make the Net object static, and access it in a static way like Net.blalba. Doing so i could access the Net functions from anywhere in the application by just calling Net.things
    If it were not static, i would have to send along either the App reference or the Net reference to anything that should use it... Seems kind of exhausting...
    What is the GOOD way of doing this?

    OK, so its the static approach?
    Not sending around references to an object, but use it static instead?
    Now i have the "App" holding a static object of "Net" and in net we have a function called send(). Off course the net object is only made as one instance (singleton).
    So, whenever i wanna call the send() i do App.net.send(); From anywhere withing the program.
    Instead of sending the net object to any parts of the program that needs to access send...

  • Non-static and static errors

    Hi,
    I've created a couple classes, say, Input and Output both with a number of different methods.
    Output holds an integer value that Input needs access to.
    I created a method in Output to return the value, such as
    //doneItemCount is declared up here somewhere, etc
    public int items()
         int returnvalue = doneItemCount;
         return returnvalue;
    My Input class has a method from which it tries to get that value
    public void blah()
    int test = Output.items();
    but no matter what i try i get
    non-static method items() cannot be referenced from a static context
    int test = Output.items();
    If i make the methods static, then i get the same error for doneItemCount not being static or whatnot.
    Any tips on how to overcome this?
    Thanks

    Hi!!
    This error means that you are mixing up static and non-static methods. If you keep items() as you wrote it, then it's not a static method, and you'll have to create or use an Output variable in the blah() method. If I'm not clear:
    In Output, you put:
    public int items()
    return doneItemCount;
    And in Input, you put either:
    public void blah()
    int test = new Output().items();//not very useful
    or, if you declared and instanciated an Output variable(say blabla) somewhere else in the Input class, you put:
    public void blah()
    int test = blabla.items();
    Anyway, you should keep items() non-static, since it needs to access to an attribute(doneItemCount).
    Hope this'll help. When I first met this error, I thought it was quite a weird solution, but you get used to it. And the compiler leaves you alone :).

  • 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.

Maybe you are looking for

  • How to add attribute to Item ?

    Hi, I have a problem concerning OCS -> Content Service. I try to find out how scaleable the tool is. Do you know is it possible to add attribute to the Item? For example how to add some link to Document in repository? Best regards

  • I'm getting ticked off!

    I have spent all afternoon/early evening trying in vain to get iTunes 7 to play a song. No luck. Apparently Apple has released a Beta version because that's what it's acting like. I can't even play internet radio stations. Of course, videos play on i

  • Trying to switch primary displays without being able to see

    my roommate has an Intel iMac Duo and the built-in monitor is not working. the image is totally obscured by tiny lines. only faint shades can be made out and it's not usable. he bought a miniDVI > DVI adapter and a DVI > HDMI adapter and connected hi

  • Fillable form will not print the second page

    I have created a fillable two-page Acrobat form using Adobe InDesign.  Everything appears to be okay with the form, except that the second page does not print.  The first page prints okay, but the second page exits as a blank page without content fro

  • Merging multiples of the same photo into one

    I remember reading a couple tutorials on how to do this weeks ago, but now i cannot seem to remember what to search for to find a tutorial on this. I multiple photos, its the same location (tripod) with me in a different position in each frame. I wan