Static Variable in webapplication

Are the values of static variables preserved when two different users try and access them? i.e.
If one web application user sitting in Chicago sets a static variable to 'true' from 'false'. Will the other user sitting in Omaha see it as 'true' or 'false' in his session?

Alright, I did this test.
1) On my local tomcat I created a mini webapp where I
declared a static which populates from a form field.
static String displayname = "";
displayname = request.getParameter("username");
and then displayed it on the html page.
2) I opened IE sessions of my application and in one
I gave the user name 'Tom' and other 'Janet' and hit
continue. (Tom before Janet)
3) The page that had 'Tom' displayed tom and other
one Janet. Then I refreshed the display page for the
tom instance and it still showed 'Tom'.
Conclusion: It appears that the statics are indeed
loyal to the class loader and not the JVM. Hence, for
multiple users each instance should have its own
static.
Please let me know if you disagree or see my test to
be wrong.
Thanks
Message was edited by:
Birthdayhitting the refesh button on your IE page doesn't show you what the value of the static variable in your web app is. You're headding for trouble.
EDIT: Ok well it depends on you implementation how the refresh will work, but if you have a static fields in a class on your web server I promise you it's not in any way associated with any session.

Similar Messages

  • Error on compile - non-static variable can not be referencedfrom static con

    Error on compile happening with addButton?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    public class Log implements ActionListener {
    JButton addButton;
    public static void addComponentsToPane(Container pane) {
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
         c.gridy = 3;
    c.gridx = 0;
         JLabel callsignLabel= new JLabel("Callsign");
    pane.add(callsignLabel, c);
         c.gridy = 3;
    c.gridx = 1;
         JLabel nameLabel= new JLabel("Name");
    pane.add(nameLabel, c);
         c.gridy = 3;
    c.gridx = 2;
         JLabel timeLabel= new JLabel("Time");
    pane.add(timeLabel, c);
         c.gridy = 3;
    c.gridx = 3;
         JLabel dateLabel= new JLabel("Date");
    pane.add(dateLabel, c);
         c.gridy = 3;
    c.gridx = 4;
         JLabel frequencyLabel= new JLabel("Freq ");
    pane.add(frequencyLabel, c);
         c.gridy = 3;
    c.gridx = 5;
         JLabel locationLabel = new JLabel("Country/State");
    pane.add(locationLabel, c);
    c.gridy = 5;
    c.gridx = 0;
         addButton = new JButton("Add");
    pane.add(addButton, c);
         addButton.addActionListener(this);

    Thank you for the reply
    I am new to Java
    What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
    If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again.

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • Loading the final static variables at run time.. Please help

    Hello, fellow developers & Gurus,
    Please help me figure out the best way to do this:
    I need to load all my constants at run time. These are the public static final instance variables. The variables values are in the DataBase. How do I go about loading them.

    Your original question was diffeent, but your further posts show what you really want to do:
    1) all constants in 1 class
    2) available readonly for other classes
    3) updatable during runtime by changing in the database
    Did I understand you right?
    Then smiths' approach solves point 2):
    Instead, make the variables available through a method
    call - that way you avoid the whole final variable
    versus read-only attributes problem.
    //GLOBAL VARIABLES EXPOSED AS PUBLIC PROPERTIES
    public final class GlobalProperties
    public static int getTableSize();
    public static int getRowSize();
    Each "constant" should be a private static variable, and these methods simply return their values.
    The variables are initialized in a static initializer by accessing the db. Ok.
    You habe a table with one row containing as columns all the constants.
    A method readConstants() does a "select constant1, constant2, ... from const_table" and sets all the variables.
    The static initializer calls this method.
    Right?
    Ok, then you simply call readConstants() everytime you want to synchronize with the actual content of const_table.
    Was it this?

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • Non-static variable Help needed

    Hi, I am creating a multi threaded web server but get the following error
    non-static variable this cannot be referenced from a static context
    HttpRequest request = new HttpRequest(connectionSocket);
    Please could someone help.
    Many Thanks
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public static void main(String argv[]) throws Exception
         // Set the port number.
         int port = 6789;
    // Establish the listen socket.
                   String fileName;
                   ServerSocket listenSocket = new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while (true) {
         // Listen for a TCP connection request.
         Socket connectionSocket = listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request = new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread = new Thread(request);
    // Start the thread.
    thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
              socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
         try {
              processRequest();
         } catch (Exception e) {
              System.out.println(e);
    private void processRequest() throws Exception
         // Get a reference to the socket's input and output streams.
         //InputStream is = new InputStream(socket.getInputStream());
         //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
                        new BufferedReader(new InputStreamReader(
                             socket.getInputStream()));
                   DataOutputStream outToClient =
                        new DataOutputStream(
                             socket.getOutputStream());
         // Set up input stream filters.
         requestMessageLine = inFromClient.readLine();
         //BufferedReader br = null;
         // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
                             new StringTokenizer(requestMessageLine);
                   if (tokenizedLine.nextToken().equals("GET"))
                        fileName = tokenizedLine.nextToken();
                        if ( fileName.startsWith("/")==true )
                             fileName = fileName.substring(1);
    File file = new File(fileName);
                        int numOfBytes = (int)file.length();
                        FileInputStream inFile = new FileInputStream(fileName);
                        byte[] fileInBytes = new byte[numOfBytes];
                        inFile.read(fileInBytes);
                        /* Send the HTTP header */
                        outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
                        if (fileName.endsWith(".jpg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".jpeg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".gif"))
                             outToClient.writeBytes("Content-Type: image/gif\r\n");
                        if (fileName.endsWith(".html"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        if (fileName.endsWith(".htm"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
                        outToClient.writeBytes("\r\n");
                        /* Now send the actual data */
                        outToClient.write(fileInBytes, 0, numOfBytes);
                        socket.close();
                   else
                   System.out.println("Bad Request Message");
                   todaysDate = new Date();          
                   try {
                        FileInputStream inlog = new FileInputStream("log.txt");
                        System.out.println(requestMessageLine + " " + todaysDate );
                        FileOutputStream log = new FileOutputStream("log.txt", true);
                        PrintStream myOutput = new PrintStream(log);
                        myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
                   catch (IOException e) {
                   System.out.println("Error -> " + e);
                   System.exit(1);
    socket.close();

    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public MultiWebServer(){
    try{
    // Set the port number.
    int port=6789;
    // Establish the listen socket.
    String fileName;
    ServerSocket listenSocket=new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while(true){
    // Listen for a TCP connection request.
    Socket connectionSocket=listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request=new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread=new Thread(request);
    // Start the thread.
    thread.start();
    }catch(IOException ioe){
    }catch(Exception e){
    public static void main(String argv[]) throws Exception
    new MultiWebServer();
    final class HttpRequest implements Runnable
    final static String CRLF = "\r\n";
    Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
    // Constructor
    public HttpRequest(Socket socket) throws Exception
    this.socket = socket;
    socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
    try {
    processRequest();
    } catch (Exception e) {
    System.out.println(e);
    private void processRequest() throws Exception
    // Get a reference to the socket's input and output streams.
    //InputStream is = new InputStream(socket.getInputStream());
    //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
    new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
    DataOutputStream outToClient =
    new DataOutputStream(
    socket.getOutputStream());
    // Set up input stream filters.
    requestMessageLine = inFromClient.readLine();
    //BufferedReader br = null;
    // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
    new StringTokenizer(requestMessageLine);
    if (tokenizedLine.nextToken().equals("GET"))
    fileName = tokenizedLine.nextToken();
    if ( fileName.startsWith("/")==true )
    fileName = fileName.substring(1);
    File file = new File(fileName);
    int numOfBytes = (int)file.length();
    FileInputStream inFile = new FileInputStream(fileName);
    byte[] fileInBytes = new byte[numOfBytes];
    inFile.read(fileInBytes);
    /* Send the HTTP header */
    outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
    if (fileName.endsWith(".jpg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".jpeg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".gif"))
    outToClient.writeBytes("Content-Type: image/gif\r\n");
    if (fileName.endsWith(".html"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    if (fileName.endsWith(".htm"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
    outToClient.writeBytes("\r\n");
    /* Now send the actual data */
    outToClient.write(fileInBytes, 0, numOfBytes);
    socket.close();
    else
    System.out.println("Bad Request Message");
    todaysDate = new Date();
    try {
    FileInputStream inlog = new FileInputStream("log.txt");
    System.out.println(requestMessageLine + " " + todaysDate );
    FileOutputStream log = new FileOutputStream("log.txt", true);
    PrintStream myOutput = new PrintStream(log);
    myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
    catch (IOException e) {
    System.out.println("Error -> " + e);
    System.exit(1);
    socket.close();

  • Non-static variable being used in static context

    I am currently attempting to write a basic user login system using basic applets. I have two JTextFields named "userText" and "passText".
    What i am attempting to do is use the ".getText()" method to get the text out of the JTextField and verifying the string against a string already in a file using the bufferedReader, etc.
    However when i try to compare the string in the file with the one in the text field using the following code:
    if ((line.compareTo(username)) == 0)
    i get the following error...
    "non-static variable being used in a static context"
    Any ideas?

    The static method doesn't know about instances of the class instead you pass the instance to the method:
    static public void myMethod(MyClass instance, String var) {
      if(instance.line.compareTo(var))
    And then the call would be:
    MyClass.myMethod(anInstance, userName);

  • How to give different value to a static variable???

    Hi all:
    Is there any solution to set different values to a static variable???I had try two ways but all have errors!
    1.Way_1
    protected String tmp=null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    tmp = "string1";
    else if (sayorpress==1)
    tmp = "string2";
    protected static String RESOURCE_STRING = tmp; <---error
    Error:non-static variable tmp cannot be referenced from a static context
    2.Way_2
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    protected static String RESOURCE_STRING = "string1"; <---error
    else if (sayorpress==1)
    protected static String RESOURCE_STRING = "string2"; <---error
    Error:illegal start of expression at
    not an expression statement at
    Thank you very mich!!!

    Try this:
    protected static String RESOURCE_STRING = null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    yourClass.RESOURCE_STRING = "string1";
    else if (sayorpress==1)
    yourClass.RESOURCE_STRING = "string2";
    You cannot declare a static variable inside a method. But you can access a static variable thorugh your class.

  • Runtime error in linking with static variables....

    Hi,
    I am building a shared library which includes a compiled object generated from a class containing the static variables only and also I have another version of same class with same & some new static variables in it and using that to generate another shared library. Now when I tried to run a program
    which links with both the library it core dumps when it tries to return from the program i.e when it finishes.
    Can someone please help me explain why my program is behaving like that?? Can duplicate inculsion of static variables in different scope can cause problem ?? How can this be avoided ?
    Also please be advised that the class with static variables gets generated at the compile time using a script which uses a DTD whose version (specification) can be different in both the libraries therefore I can't just seperate the common stuff into one class and specific into another.
    Thanks.
    Rajeev.

    Not to worry...found the answer in another post. Seems like patches need to applied to the OS.

  • Main method hangs setting static variable

    I have a very annoying intermittent problem. Once in a while (roughly 1 out of 30 times), my app hangs in the main method when assigning a value to a static variable.
    public static void main(String[] args) {
    //read args
    //do some very trivial stuff (never hangs here)
    someOtherNonStaticClass.aStaticInt = 100;//once in a while it hangs here???
    }I have tried setting "-Dsun.java2d.noddraw=true" but this hasnt helped. I have tried using JRE 1.4.1 and 1.4.2 and they both have this problem. Some machines seem to be worse than others but this may just be chance.
    When the app hangs, it appears in task manager as a javaw.exe process, but the app itself doesnt appear.
    Does anyone have any ideas or suggestions for me to try? Its pretty annoying not have a stack trace to work with.

    I have tried setting "-Dsun.java2d.noddraw=true" butWhy should it?
    this hasnt helped. I have tried using JRE 1.4.1 and
    1.4.2 and they both have this problem. Some machines
    seem to be worse than others but this may just be
    chance.
    When the app hangs, it appears in task manager as a
    javaw.exe process, but the app itself doesnt appear.That's normal. All Java apps would appear as javaw.exe. Because the JVM has the process.
    Does anyone have any ideas or suggestions for me to
    try? Yes. Stop accessing fields of another class. It's bad design to begin with, and it looks to me like you're breaking something someplace else by setting that value to 100 right then.

  • To use a static variable in another class,but report NullPointerException

    when TableMain is running,I run testRecord so that let TableMain add a occur informatin and
    happened time in a row in TableMain,but when I run testRecord,java report a NullPointerException and I dont know how to solve this problem,thanks for helping me to check my code;(error report info is in end)
    import java.awt.event.*;
    import javax.swing.table.*;
    import java.io.*;
    public class TableMain extends JFrame{
    JTable table;
    static OwnModel model;
    String[] columnHeader={"occur","time"};
    class OwnModel extends DefaultTableModel{
    public OwnModel(Object[] columnNames,int numRows){
    super(columnNames,numRows);
    public boolean isCellEditable(int row,int column){
    return false;
    public TableMain(){
    model=new OwnModel(columnHeader,0);
    table=new JTable(model);
    JScrollPane scroll=new JScrollPane(table);
    JButton save=new JButton("save record");
    JButton delete=new JButton("delete record");
    JPanel buttons=new JPanel();
    buttons.add(save);
    buttons.add(delete);
    JLabel sign=new JLabel("occur record");
    Container cp=getContentPane();
    cp.add(BorderLayout.NORTH,sign);
    cp.add(BorderLayout.CENTER,scroll);
    cp.add(BorderLayout.SOUTH,buttons);
    this.setSize(300,500);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String[] args){
    new TableMain();
    import java.util.Vector;
    import java.util.Calendar;
    import java.text.SimpleDateFormat;
    public class testRecord{
    public static void main(String[] args){
    SimpleDateFormat simpledf=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    String tableName="friends";
    Calendar occurtime=Calendar.getInstance();
    Vector record=new Vector();
    record.add("send 'desc' sql, "+"operated table is :"+tableName);
    record.add(simpledf.format(occurtime.getTime()));
    System.out.println("model is "+Guide.model);
    System.out.println("record is "+record);
    Guide.model.addRow(record);
    error report:
    model is null
    record is [send 'desc' sql,operated table is :friends, 2004/05/26 11:39:03]
    Exception in thread "main" java.lang.NullPointerException
    at testRecord.main(testRecord.java:14)

    but I just use this constructor once,never use twice
    with same jvm;I thinks my idea is not too very badIt's a public constructor (if I'm looking in the right
    place) - it could be called from anywhere. To
    intialize a static variable outside the declaration,
    use a static initializer:private static String whatever;static {
    whatever = "whatever";
    }Or simply (in this case):private static String whatever = "whatever";

  • Static variable in cluster

    Hi All,
              How does WebLogic cluster an object, EJB or servlet, with
              static variables? I mean, will the static variables in multiple
              JVMs still have a single value? Or it just can't be clustered?
              Lynch
              

    Statics are only statics per JVM and classloader. This applies to non
              clustering environments as well. If you want a singleton you have to use
              another approach.
              Tinou Bao
              www.tinou.com
              "Lynch" <[email protected]> wrote in message
              news:3b170adb$[email protected]..
              > Hi All,
              >
              > How does WebLogic cluster an object, EJB or servlet, with
              > static variables? I mean, will the static variables in multiple
              > JVMs still have a single value? Or it just can't be clustered?
              >
              > Lynch
              >
              >
              

  • Static variable in session bean

    Can we declare static variable in session bean. If we declare what will happen. Will it create error in compile time or not deployed in server.

    From a Java language perspective, nothing stops you from declaring a static variable in a session
    bean class. It will compile as long as its syntactically correct.
    From an EJB programming model perspective, the use of non-final static variables
    is discouraged because it breaks the JVM-transparency that is an important aspect of the
    EJB architecture. It should be possible to deploy a single EJB application to a cluster and
    have it behave exactly as if it were deployed to only one server instance (albeit with higher
    overall throughput/performance). Using non-final static variables breaks this property
    because the bean instances in one JVM will see a different value for the static variable
    than bean instances in a different JVM.
    It also forces you to deal with synchronization
    of the shared data, which is a complexity that was carefully avoided in the EJB programming
    model by ensuring that each bean instance is single-threaded.
    Bottom line is you can have "final static" data members in EJB classes but you should
    avoid non-final (mutable) static data.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

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

Maybe you are looking for

  • Video Settings for WoW on new iMac.

    Just got a new iSight iMac and World of Warcraft. Running 1GB of ram. There are a bunch of video settings in this game that can be adjusted. Suggestions or would it best to just leave them on default.

  • What APN and settings do I use the iPad 2 T Mobile 3G connectivity

    hello got my nano SIM from my iPad 2 from T Mobile and I like to know what are the APN settings I should use I can get 3G connectivity.

  • Agent greeting delay

    Dear Community, My UCCE 8.5 setup is experiencing agent greeting delay, where once the call is connected to agent, there are 2secs delay (silent) before the agent greeting file played (heard). The setup is centralized servers with VG and IP phones re

  • Inforecord - set MAIN_VENDOR

    Hi gurus, how can I set the MAIN_VENDOR (EINA-RELIF) on an inforecord of a material? It seams that the function module ME_UPDATE_INFORECORD cannnot handle this feld - or am I calling the FM in the wrong way? Thanks, Manuel

  • Como fazer a musica tocar junto com o video

    BRASIL >>   Quero que a musica toque quando passo o mouse em cima na hora da edição! como faço? EUA >>   I want the song when step touch the mouse over the edit time! how do I?