What is static variable.

What is static variable. what is difference between  static variable and public variable?

Static variables belong to the Class. Non-static variables belong to Class instances.
Public variables can be accessed from outside of the Package. Non-public variables can only be accessed within the Package.
So they are quite different thing. You can have Static variables, Public Static variables, and Private Static variables...

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.

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

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

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

    I have a multithreaded servlet and a counter variable to keep count of when each thread finishes executing.
    I have set the variable to be a static integer.
    The problem is that the counter variable persists across requests whereas I want it to reset with each request. What should I do?

    Thanks a lot. It works.
    I set the counter =1 in the variable passed to the thread and set it as a static variable in the thread definition.
    Thanks once more.

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

    There may be more errors in here besides the static variable error. I made the methods static for the method call in my constructor Product(name, price). The purpose of this Class is to the the name and price of a product from user input, subtract 5.00 from the price, and return the new price. Please help!!!
    public class Product
    public Product(String name, double price)
    String product;
    price = Product.getPrice(price);
    Double.toString(price);
    //this.product = product;
    product = Product.getName(name) + Product.getPrice(price);
    public static String getName(String name)
    System.out.println("What is their name?: ");
    name = in.nextLine(); // I GET A NONSTATIC VARIABLE ERROR FOR variable "in" HERE.
    return name;
    public static double getPrice(double price)
    this.price = price;
    System.out.println("What is the price?: ");
    price = in.nextDouble();
    return price;
    public double reducePrice()
    price = price - 5.00;
    return price;
    public String getProduct()
    product = new Product(name, price);
    return product;
    Scanner in = new Scanner(System.in);
    public static String name;
    //public double price;
    }

    you not define the class member properly.
    the class member is define before the constructor as
    public class Product {
         static Scanner in = new Scanner(System.in);
         String product;
         double price;
         public static String name;
         public Product(String name, double price) {
              price = Product.getPrice(price);
              Double.toString(price);
              // this.product = product;
              product = Product.getName(name) + Product.getPrice(price);
    }

  • Non static variable?

    i've a small problem with an object.
    public class klassenobjekttest
    public static void main(String[] args)
    Auto meinFahrzeug;
    meinFahrzeug = new Auto();
    meinFahrzeug.name = "Porsche";
    meinFahrzeug.erstzulassung = 1933; // woher soll ich das wissen?
    meinFahrzeug.leistung = 300;
    System.out.println("Fahrzeug name: " + meinFahrzeug.name);
    System.out.println("Fahrzeug Erstzulassung: " + meinFahrzeug.erstzulassung);
    System.out.println("Fahrzeug Leistung: " + meinFahrzeug.leistung);
    class Auto
    public String name;
    public int erstzulassung;
    public int leistung;
    the sdk says:
    klassenobjekttest.java:6: non-static variable this cannot be referenced from a s
    tatic context
    meinFahrzeug = new Auto();
    ^
    1 error
    what's wrong?

    However if i use:
    public class klassenobjekttest
    Auto meinFahrzeug;//brought this line out of main
    public static void main(String[] args)
    meinFahrzeug = new Auto();
    meinFahrzeug.name = "Porsche";
    meinFahrzeug.erstzulassung = 1933; // woher soll ich das wissen?
    meinFahrzeug.leistung = 300;
    System.out.println("Fahrzeug name: " + meinFahrzeug.name);
    System.out.println("Fahrzeug Erstzulassung: " + meinFahrzeug.erstzulassung);
    System.out.println("Fahrzeug Leistung: " + meinFahrzeug.leistung);
    class Auto
    public String name;
    public int erstzulassung;
    public int leistung;
    It does not work.
    could somebody tell me why.
    Appreciate the help
    Thanks,
    Preetham.

  • Non static variable errors

    I have been working on this file for 4 days now and I can't get past these errors.
    Here's the whole project:
    package toysmanager;
    public class ToysManager {
    //Method ToysManager
    public ToysManager() {
    //Method main
    public static void main(String[] args) {
    ToddlerToy Train1 = new ToddlerToy();
    ToddlerToy Train2 = new ToddlerToy();
    ToddlerToy Train3 = new ToddlerToy();
    System.out.print("This is an object of type ToysManager");
    Train1.PrintProductID();
    Train2.PrintProductID();
    Train3.PrintProductID();
    public class ToddlerToy{
    private int ProductID = 0;
    private String ProductName = "";
    private float ProductPrice = 0;
    public ToddlerToy(int id,String name, float price){
    ProductID = id;
    ProductName = name;
    ProductPrice = price;
    //Method PrintProductID
    public int PrintProductID(){
    System.out.print("This method is PrintProductID in the class ToddlerToy");
    System.out.print("Product ID is:" + ProductID);
    return ProductID;
    public String PrintProductName(){
    System.out.print("This method is PrintProductName in the class ToddlerToy");
    System.out.print("Product Name:" + ProductName);
    return ProductName;
    public float PrintProductPrice(){
    System.out.print("This method is PrintProductPrice in the class ToddlerToy");
    System.out.print("Product Price: $" + ProductPrice);
    return ProductPrice;
    And here are the errors:
    "ToysManager.java": non-static variable this cannot be referenced from a static context at line 9, column 29
    "ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 9, column 29
    "ToysManager.java": non-static variable this cannot be referenced from a static context at line 10, column 29
    "ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 10, column 29
    "ToysManager.java": non-static variable this cannot be referenced from a static context at line 11, column 29
    "ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 11, column 29
    Any help would be appreciated as I am plainly not understanding this even with a book.

    Annie:
    Could you help me understand the original ToyManager instructions more please? Not asking you to do the work for me I just do not understand exactly what they want me to do...
    Assignment:
    After you install JCreator, write a Java program, with a single class called ToysManager. The main method should print the name of the class, for example: "This is an object of type ToysManager."
    (Hint: the process is very similar to the "Hello World!" program.)
    Please add file (.java)
    Group Portion:
    Deliverables:  two *.java files
    As a group, add a second class called ToddlerToy to your ToysManager project.
    Here are  the requirements for the ToddlerToy:
        * The class ToddlerToy is public and has a default constructor.
        * It  has  one private attribute called  ProductID (of type int).
        * It has two public  methods called  SetProductId() and PrintProductId().
        * The method SetProductId() assigns a value to the attribute ProductId. For now, the value is hard-coded.
        * The method  PrintProductId prints the value of the attribute ProductId.
        * The class ToddlerToy has no main() method.  In Java, there is only one main method for the entire program. In this case, the main method is in the ToysManager class.
    Here are the requirements for the main method of the ToysManager class:
        * Create an object called Train1 of  class  type ToddlerToy, using the default  constructor.
        * Call the methods SetProductId() and PrintProductId() to set then print the the value of ProductId.
        * The first statement  in each method should print the name of the method, for example:  "This is method <method name> in class <class name>". This should help you trace the execution of your program. Feel free to comment out the print statement.
        * On the Small Group Discussion Board, discuss your understanding of the concepts of class, object, constructor, method, and attribute.
        * Give one example of a class (giving its name, attributes, and methods)  that could be part of the shipping application.ANY help with this at all is greatly appreciated...a friend of mine found your post and used it to give me code snippets for help and I had no idea. Nearly got me in deep water...redoing the assignment but personally I find the next two assignments much easier to understand than this one. The instructions are confusing to me...can you point me in the right direction?

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

Maybe you are looking for

  • Jquery Slideshow problem in IE

    I have a Jquery slideshow on my page and it works alright in FireFox but in Internet Exploer 8, the transaction between the JPEG photos are not smooth. Can someone help me out as to what coding i would need to make the slideshow smooth in IE8 or lowe

  • Authorization error when viewing the contents of a cube.

    Hi all, I created a cube,loaded data into it.  When I want to view the contents I get this below error... any clues on how to debug this..... Your user master record is not sufficiently maintained for object Commodity and Company Code Auth object Mes

  • Problem upgrading Studio 5 to JDK 1.5.0

    Running Solaris Studio with JDK 1.4.2 for many months, but having a hard time upgrading to 1.5 Error: Class file has wrong version 49.0 should be 48.0 I assume that I am somehow compiling/executing under both 1.5 and 1.4.2, but can't figure out how t

  • Copy-into-Safari causes crash of all, in 10.4 & 10.5

    My two computers -- iMac with 10.4.11 & Safari 3.2, and MB-Pro with 10.5.6 & Safari 3.2.1 with no Safari plug-ins -- are stable except sometimes when I "copy" into Safari (in URL field or a web-page field) which causes the Spinning Ball to appear, an

  • Importing business definitions

    I hava followed [this topic|http://www.oracle.com/technology/obe/10gr2_owb/owb10gr2_gs/owb/lesson7/bi-modeling.htm]. I'm using OWBluider 11g, after Business Definitions deployment,it was necessary import .eex file through Oracle Discoverer Admininstr