"this" statement in a static context?

I get the error: "Cannot use this in a static context", but why??
public class This {
    public int add(int a){
        a = a+a;
        return a;
    public static void main(String[] args) {
        this.add(2);
}

You simply need an instance to work with. Instantiate one. Rewrite your code this way:
public class This
    public int add(int a)
        a = a+a;
        return a;
    public static void main(String[] args)
       This t = new This();   
        t.add(2);
}%

Similar Messages

  • Cannot use this in a static context

    I have a static method in which I am trying to use a logging class. I get an error that says "Cannot use this in a static context" when I compile the following code.
    Log log = LogFactory.getLog(this.getClass());What's the problem and how do I get around it?

    1) What's the problem.
    The error states the problem concisely. You are trying to use this[b] to get the class. You can't do this in a static method.
    2) How do I get around it...
    Instead of typing this.getClass() you type <CLASS_NAME>.classwhere CLASS_NAME is the name of the class the static method is in.

  • Non-static variable total cannot be referenced from a static context

    i am trying to write a program that uses the if-else statements and when i wrote my program i got "non-static variable total cannot be referenced from a static context" for three lines of my input.
    A:\Disks.java:20: non-static variable total cannot be referenced from a static context total = (10000 * .95 + ((diskCount - 10000) * .85));
    ^
    A:\Disks.java:22: non-static variable total cannot be referenced from a static context total = (diskCount * .95);
    ^
    A:\Disks.java:24: non-static variable total cannot be referenced from a static context System.out.print(total);
    ^
    Do you know what I did wrong?

    I apologise in advance for the general tone of this reply.....
    Ummm, let me think for a second... You referenced a non static
    variable from a static context. Yup, yup. That's it !
    If you can't figure this out, you really need to do a Java tutorial or
    buy a text book. Basically though, total is a member of some class
    and you are trying to use it from a static function. I bet you have
    something like:
    public class Test {
        public int total;
        // blah blah blah
        public static void main(String[] args) {
            // This won't work cos "total" is a member and we are static
            System.out.println(total);
            // This works cos now you have an instance to pull total
            // out of.
            Test t = new Total();
            System.out.println(t.total);
    }

  • Does class/static context make an object?

    Howdy all!
    I know that for every class there exists a 'static context' in which all static members of a class operate - methods, variables or classes.
    I also know that there is a method getClass() which retrieves a Class object.
    My question is: does this mean that Java considers the class or static context of a class to be an object in its own right?
    Having static members of a class implies that you have a static state - and an obvious choice is to have an object to store that state.
    Is this correct? Is there something I have missed?
    Rob

    Hi,
    Being no expert, I would say that you are on the right track. Each class loaded by a java.lang.ClassLoader is represented in Java by an object of class java.lang.Class.
    The static memebers of a class are local to this instance of the class. This can be easily verified by loading the same class two times (can be done, for example, by writing your own ClassLoader). Then when you set a static member in an object of the first class, you will not see the change in objects instantiated from the later class, although it is of the same type.

  • Static Context: What Does it REALLY mean?

    Friends,
    I really having this trouble of grabbing the idea of static context vs non-static context.
    Lets say I have a static method, is that mean that all items (variables and calls) inside it are assumed to be static as well?
    Thanks in advance.

    Any statement or expression inside the static method is said to "occur in a static context". In such a method - like the traditional main() method - only static members and methods can be used.
    (Statements and expressions occuring in lots of other places are also said to occur in a static context - see the JLS http://java.sun.com/docs/books/jls/third_edition/html/classes.html#296300 for details. In a loose sense what these contexts have in common is that they "belong" to the class as a whole, rather than to any specific instance: they relate to class wide things and operations.)

  • Non-static variable cant accessed from the static context..your suggestion

    Once again stuck in my own thinking, As per my knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static context....'
    Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void main(String ar[]){      ////static context
    ������������ int counter=0; ///Non static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    �������������� System.out.println("Value of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    Jeff

    Once again stuck in my own thinking, As per my
    knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static
    context....'
    Now the thing is that, When we are declaring any
    variables(non-static) and trying to access it within
    the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void
    main(String ar[]){      ////static context
    ������������ int counter=0; ///Non
    static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    ��������������
    System.out.println("Value
    of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    w the question is that if we are trying to declare a
    variable out-side the method (Non-static) , Then we
    defenately face the error' Non-static varialble can't
    accessed from the static context', BUT here within
    the static context we declared the non-static
    variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    JeffHi,
    You are declaring a variable inside a static method,
    that means you are opening a static scope... i.e. static block internally...
    whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
    But if you put ... it will be considered as redundant by compiler.
    More over, static context does not get "this" pointer...
    that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller.

  • Non-static variable from a static context

    This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
    The error...
    Googler.java:27: non-static variable this cannot be referenced from a static context
              submitButton.addActionListener(new ButtonHandler());The code...
              JButton submitButton = new JButton("Submit Query");
              submitButton.addActionListener(new ButtonHandler());

    thanks for the response.
    I have already tried what you said but I tried it again anyway and i get the same error more less...
    Googler.java:28: non-static variable this cannot be referenced from a static context
              ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
    public class Googler
      static JTextField input1, input2;
         public static void main(String[] args)
              JFrame myFrame = new JFrame("Googler v1.0");
              Container c = myFrame.getContentPane();
              JLabel lab1 = new JLabel("Enter Google Query:");
              JLabel lab2 = new JLabel("Enter Unique API Key:");
              input1 = new JTextField(15);
              input2 = new JTextField(15);
              JRadioButton radSearch = new JRadioButton("Search Query");
              JRadioButton radCached = new JRadioButton("Cached Query");
              JButton submitButton = new JButton("Submit Query");
              ButtonHandler buttonHandler = new ButtonHandler();
              submitButton.addActionListener(buttonHandler);
              ButtonGroup group = new ButtonGroup();
              group.add(radSearch);
              group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
    Thanks
    Lee

  • Non-static variable from static context?

    Hi,
    I've created a program using swing components
    and I've set up a addActionListener to a button,
    button.addActionListener(this);
    when try and compile I get the following error:
    non-static variable this cannot be referenced from a
    static context
    button.addActionListener(this);
    I've checked site and my notes I don't seem to have
    done anything different from programs that have compiled
    in the past.
    I'm currently doing a programming course so I'm fairly
    new to Java, try not to get to advanced on me :)
    Thx in advance for any help.
    Chris

    Well what is declared static? If I remeber right this error means that you have a static method that is trying to access data it does not have access to. Static methods cannot access data that is intance data because they do not exist in the instance (not 100% sure about this but I believe it is true, at the very least I know they do not have access to any non-static data). Post some more of your code like where you declare this (like class def) and where you set up the button.

  • Non static  variable in static context

    import java.util.Scanner;
    public class project4_5 {
         int die1, die2;
         int comptotal = 0, playertotal = 0, turntotal = 0;
         int turn, comprun = 0;
         String playername;
         String action = ("R");
         Scanner scan = new Scanner(System.in);
            public static void main (String[] args)
            PairOfDice mydie = new PairOfDice();
         System.out.println("!!!!!!PIG!!!!!!");
         System.out.println();
         System.out.println("Enter your name! ");
         playername = scan.nextLine();
         while(playertotal>100 && comptotal>100){
         while(action.equalsIgnoreCase("R")){
                   System.out.println(playername+" roll or pass the die (R/P) ");
                   action = scan.nextLine();
                   if(action.equalsIgnoreCase("P"))
                        break;
                   mydie.roll();
                   die1 = mydie.getFace1();
                   die2 = mydie.getFace2();
                   System.out.println("You rolled a "+die1+" and a "+ die2);
                   if(die1==1||die2==1){
                        turntotal = 0;
                        System.out.println("You rolled a 1, you lose your points"
                        +" for this turn.");
                        break;
                   else if(die1==1&&die2=1){
                        playertotal = 0;
                        System.out.println("You rolled snake eyes, all points have"
                        + " been lost.");
                        break;
                   else
                   turntotal= turntotal+die1+die2;
                   System.out.println("Would you like to roll or pass? (R/P)");
                           if(action.equalsIgnoreCase("P")){
                                playertotal = playertotal+turntotal;
                                turntotal = 0;
                   while(turntotal<=20||turns!=run){
                   turn = (int) (Math.random() * 5 + 1);
                   mydie.roll();
                   die1 = mydie.getFace1();
                   die2 = mydie.getFace2();
                   System.out.println("Computer rolled a "+die1+
                   " and a "+ die2);
                   if(die1==1||die2==1){
                        turntotal = 0;
                        System.out.println("Computer rolled a 1 he loses hi points"
                        +" for this turn.");
                        break;
                   else if(die1==1&&die2=1){
                        playertotal = 0;
                        System.out.println("Computer rolled snake eyes, his points have"
                        + " been lost.");
                        break;
                   else
                   turntotal= turntotal+die1+die2;
                   comprun++;
                   turntotal = 0;
       }here is code for a dice game i made...and when i compile it practically every variable gets an error saying non-static variable can not be referenced from a static context....anyone kno what this means or how i go about fixing it...i think it has something to do with assigning the return variable from my getFace method to die1 and die 2...idk how to fix it tho
    if u need it my die class is below
    public class PairOfDice
         int faceValue1, faceValue2;
         public PairOfDice()
              faceValue1 = 1;
              faceValue2 = 1;
         public void roll()
              faceValue1 = (int) (Math.random() * 6 + 1);
              faceValue2 = (int) (Math.random() * 6 + 1);
         public int getFace1 ()
              return faceValue1;
         public int getFace2 ()
              return faceValue2;
         

    It means what it says -- that you're trying to use a non-static thing (like a method or a field) from a static thing (like your main method).
    You can either make everything static (which isn't great -- it flies in the face of object-oriented programming) or instantiate an object.
    If you want to do the latter, then try this: make your main method instantiate a method, and run it, like this:
    public static void main(String[] argv) {
        project4_5 game = new project4_5();
        game.play();
    }Then create a method called play:
    public void play() {
      // put everything that's currently in main() in here
    }See if that fixes it for you.

  • Non-static variable aceYears cannot be referenced from a static context

    This is my error...
    investment.java:53: non-static variable aceYears cannot be referenced from a static context
    lwInvest.numberAceYears(aceYears);
    ^
    This is my code...
    public static void main (String[] args)
    investment.Invest.numberAceYears(aceYears);
    and more code
    String termInvested = JOptionPane.showInputDialog
    ("Please enter the amount of years to invest your investment.");
    int intTermInvested = Integer.parseInt(termInvested);
    and yet more code..
    public void numberAceYears (int aceYears)
    for (int aY = 5 ; aY <= aceYears; aY++)
    double aceInterest = aceCoBalance * aceCoRate /100;
    aceCoBalance = aceCoBalance + aceInterest;
    aceYears = aceYears + aY;
    Suggestions?

    Short version: Either make the variable in question static, or create an instance of your class and use that to access it. Either one will work, but one probably suits your design better. It's up to you to figure out which one.
    For details, see the relevant section of your favorite Java book or tutorial, or poke around here:
    http://www.google.com/search?q=java+non+static+variable+cannot+be+referenced+from+a+static+context

  • Non-static variable change cannot be referenced from a static context

    My compiler says: : non-static variable change cannot be referenced from a static context
    when i try to compile this. Why is it happening?
    public class change{
      int coin[] = {1,5,10,25,50};
      int change=0;
      public static void main(){
        int val = Integer.parseInt(JOptionPane.showInputDialog(null, "Type the amount: ", "Change", JOptionPane.QUESTION_MESSAGE));
        change = backtrack();
    }

    A static field or method is not associated with any instance of the class; rather it's associated with the class itself.
    When you declared the field to be non-static (by not including the "static" keyword; non-static methods and fields are much more common so it's the default), that meant that the field was a property of an object. But the static main method, being static, didn't have an object associated with it. So there was no "change" property to refer to.
    An alternative way to get this work, would be to make your main method instantiate an object of the class "change", and put the functionality in other instance methods.
    By the way, class names are supposed to start with upper-case letters. That's the convention.

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Non static method cannot be referenced from a non static context

    Dear all
    I am getting the above error message in my program.
    public void testing(Vector XY){
    RecStore.checkUnits(XY);
    }method checkUnits is non static and cannont be called from a non static context. I don't see the word static anywhere...
    I have done a wider search throughout the main class and I'm haven't got any static their either.
    Any ideas?
    Thanks
    Dan

    Yup
    I had pared down my code, infact it is being called from within a large if statement.Irrelevant.
    But the same thing still holds that there is no static keyword used.Read my previous post. Calling checkUnits using the class name:
    RecStore.checkUnits(XY);implies a static context--in order for that call to work, checkUnits must be static. That's what your error message is saying--you are trying to call the non-static method "checkUnits" from the static context of using the class name "RecStore."

  • Cannot be referenced from a static context

    im trying to link my user interface to the Game class to jump,
    i get the error - non static method jump() cannot be referenced from a static context
    private void jButton1_actionPerformed(ActionEvent e)
              System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
              // code
    Game.jump();
    any ideas? thanks

    ah, it works if i change jump() to static
    i was now wondering how to make the user interface
    work with this ethod in the Game() class
    private void goRoom(Command command)
    if(!command.hasSecondWord()) {
    // if there is no second word, we don't know where to go...
    System.out.println("Go where?");
    return;
    String direction = command.getSecondWord();
    // Try to leave current room.
    Room nextRoom = currentRoom.getExit(direction);
    if (nextRoom == null)
    System.out.println("There is no door!");
    else {
    currentRoom = nextRoom;
    System.out.println(currentRoom.getLongDescription());
    i was thinking something like
    private void jButton1_actionPerformed(ActionEvent e)
    // code
    Game.goRoom(Command north);
    it doesnt seem to like that though.. :s

  • Non-static cannot be referenced from a static context - ?

    Hi, i understand (kinda) what the error means
    i think its saying that i cannot call a non-static method "bubbleSort"
    from the static method main (correct?)
    but i dont know how to fix it...
    do i make bubbleSort
    public static void bubbleSort???
    C:\jLotto\dataFile\SortNumbers.java:80: non-static method bubbleSort(int[]) cannot be referenced from a static context
              bubbleSort( a ); //sort the array into ascending numbers
    my code:
    import java.io.*;
    import java.util.*;
    public class SortNumbers
         public static void main( String args[]) throws IOException
          int num;
              int a[] = new int[7]; //an array for sorting numbers
              File inputFile = new File("C:\\jLotto\\dataFile\\outagain.txt");
              File outputFile = new File("C:\\jLotto\\dataFile\\sortedNum.txt");
            BufferedReader br = new BufferedReader( new FileReader( inputFile ));
          PrintWriter pw = new PrintWriter( new FileWriter( outputFile ));
          String line = br.readLine();
          while( line != null ){//reads a single line from the file
             StringBuffer buffer = new StringBuffer(31);          //create a buffer
             StringTokenizer st = new StringTokenizer( line," "); //create a tokenizer
             while (st.hasMoreTokens()){
                        // the first 4 tokens are id,month,day,ccyy, no sorting needed
                        // so they are simply moved into the buffer
                        for (int i =1; i<5; i++){
                             num = Integer.parseInt(st.nextToken());
                             buffer.append( num );
                             buffer.append( "|");
                        //tokens 5 to 11 need to be sorted into acending order
                        //so read tokens 5 to 11 into an array for sorting
                        for (int i =0; i<7; i++){
                             a[i] = Integer.parseInt(st.nextToken());
                     bubbleSort( a ); //sort the array into ascending numbers
                      //the array is sorted so read array back into the buffer
                      for ( int i = 0; i < a.length; i++ ){
                           buffer.append( a[ i ] );
                           buffer.append(  "|" ) ;
                   }//end of while st.hasMoreTokens
             //then write out the record from the stringBuffer
             pw.println( buffer );
             line = br.readLine();
          }//end of while != null
              br.close();
              pw.close();
         }//end of static main
       // sort the elements of an array with bubble sort
       public void bubbleSort( int b[] )
          int swapMade = 0; //if after one pass, no swaps were made - exit
          for ( int pass = 1; pass < ( b.length - pass) ; pass++ ) // passes reduced for speed
              for ( int i = 0; i < b.length - 1; i++ ) // one pass
                  if ( b[ i ] > b[ i + 1 ] )            // one comparison
                      swap( b, i, i + 1 );              // one swap
                      swapMade = 1;
                  }  // end of if
               } //end of one pass
             if (swapMade == 0) pass = 7; //no swaps, so break out of outter for loop
          }//end of passes, end of outter for loop
       }//end of bubblesort method
       // swap two elements of an array
       public void swap( int c[], int first, int second )
          int hold;  // temporary holding area for swap
          hold = c[ first ];
          c[ first ] = c[ second ];
          c[ second ] = hold;
       }   //end of swap
    }//end of class SortNumbers

    Static means
    when u run the program (a class), there is only one variabel / type in memory.
    ex static int a; //assume it's inside the aStaticClass
    mean no wonder how many u create object from this class, variabel a only have 1 in memory. so if u change a (ex a=1;) all instance of this aStaticClass will effected (because they share the same variabel).
    Try to read more at :
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html
    I hope this will help you....happy new year
    yonscun

Maybe you are looking for

  • How to Set Up Multiple Muse Files for One Site

    I'm creating a massive web site, currently over 900 pages, heavy on images and file downloads. Currently the file size is 700 MB and growing. Muse starting moving PAINFULLY slow (just pasting a text box is taking over 15 minutes, all while the rainbo

  • My iTunes library no longer matches the music on my iPhone.

    My iTunes library no longer matches the music on my iPhone.  How can I sync the music and playlists from my phone onto iTunes without iTunes completely wiping all the music on my iPhone? I'm also afraid I'll lose any newer music.

  • Problem stopping the Labview Starter Kit motors (huge offset?)

    Hi I implemented an algorythm for the Labview Starter Kit. It reads a map and navigates from the initial point to the goal. The Starter Kit only performs two movements: "go straight X mm", and "turn 90º left/right (the turning is made when stopped, l

  • After kernal panic, zeroed HD but Fresh Tiger install fails...

    Our little brave 12" PowerBook G4 started to behave a little odd today. It all started with iTunes being empty all of a sudden. And when I tried to import the old playlist, iTunes [9.2] crashed. Did this a few times when something started nagging in

  • Unable to Reinstall Muse

    The other day, I was attempting to launch Adobe Muse, and was prompted to download the latest update. I would upload the update, and Muse would appear to begin to launch its splash page. Right before the splash page would show, I would be informed th