Static class variable

Folks:
I am little confused by static class variables in Java. Since Java doesn't have global varaibles it uses static variables instead. Please take a look at the following code and please tell me what goes wrong.
/********** CONTENT OF Stack.java ***********/
import java.util.Stack;
public class StackClass
{   static  Stack stack = new Stack (); }
/********** CONTENT OF Test1 .java ***********/
public class Test1
public static void main( String[] args )
StackClass.stack.push("Hello World");
/********** CONTENT OF Test2.java ***********/
public class Test2
public static void main( String[] args )
System.out.println( "Top on stack is " + StackClass.stack.peek() );
I execute the above programs in the sequence of StackClass.java, Test1.java and Test2.java. I think in Test1.java after I push one element to the stack it should still be in the stack in Test2.java But I got :
java.util.EmptyStackException
     at java.util.Stack.peek(Unknown Source)
     at Test2.main(Test2.java:16)
Exception in thread "main"
Can anybody give me a hint?
Thanks a lot !

After you run StackClass, the JVM (java.exe) ends and all the classes are unloaded including StackClass
When you run Test1, StackClass is loaded, an item is pushed on the stack, and then the JVM exits and all classes are unloaded including StackClass
When you run Test2, StackClass is loaded, and you get an error because the StackClass which was just loaded has no items in it.

Similar Messages

  • Static class variable doesn't store ?

    Hi,
    I'm a beginner in java.
    I defined a static class variable (nodes) in th following code :
    public class MySOMapp extends javax.swing.JFrame {
         private static final long serialVersionUID = 1L;
         private static SOMTrainer trainer;
         private static SOMLattice lattice;
         private static SOMNode nodes;
         private static Hashtable nwordf; 
         public MySOMapp(String args[]) {
              SOMNode nodes = new SOMNode();          //.....But a method of this class, nodes comes null. methos definition :
    private void makesame() {I don't understand why the nodes is null in makesame method which is in the same class with nodes ?
    thanks,
    Yigit

A: static class variable doesn't store ?

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

  • Static class variable gets initialized ALWAYS

    I have the following code...
    public class SystemMonitor //extends Thread
         private static SystemMonitor SysMon;//= getInstance();
         private CLSTrackerAgent CLSTrackerAgent;// = new CLSTrackerAgent();     
         private RequestDispatcher ReqDispatcher;// = RequestDispatcher.getInstance();
         private ConnectionManager ConMgr;// = ConnectionManager.getInstance();
         private UploadManager UploadMgr;// = UploadManager.getInstance(ConMgr);
         private DownloadManager DownloadMgr;// = null;
         private FileWriter fwUploader = null;
         private FileWriter fwDownloader = null;
    //     public static void main(String args[])
         private SystemMonitor()
              try
    //               CLSTrackerAgent = new CLSTrackerAgent();     
                   ReqDispatcher = RequestDispatcher.getInstance();
                   ConMgr = ConnectionManager.getInstance();
                   UploadMgr = UploadManager.getInstance(ConMgr);
    //               DownloadMgr = new DownloadManager(CLSTrackerAgent);
                   fwUploader = new FileWriter("d://UploaderStats.xls");
                   fwDownloader = new FileWriter("d://DownloaderStats.xls");
                   String temp = "Uploader" + "\t" + "RemoteIP:Port" + "\t" + "RequestMsg" + "\t" + "Time" + "\t" + "ResponseMsg" + "\t" + "ChunkID" + "\t" + "Time" + "\t" + "TotalUploaderThreadsAlive" + "\n";
                   fwUploader.write(temp.toCharArray());
                   fwUploader.flush();
                   temp = "Downloader" + "\t" + "RemoteIP:Port" + "\t" + "RequestMsg" + "\t" + "Time" + "\t" + "ResponseMsg" + "\t" + "ChunkID" + "\t" + "Time" + "\n";
                   fwDownloader.write(temp.toCharArray());
                   fwDownloader.flush();
              catch(Exception e)
                   e.printStackTrace();
    public static SystemMonitor getInstance()
              if(SystemMonitor.SysMon instanceof SystemMonitor)
                   return SystemMonitor.SysMon;
              else
                   SystemMonitor.SysMon = new SystemMonitor();
                   return SystemMonitor.SysMon;
    I invoke the getInstance() method to get the same STATIC object that I have created. However, whenever I invoke the getInstance() method the eclipse debug utility shows SysMon = null....PLEASE HELP

    Singletons are done this way:
    public class SystemMonitor //extends Thread
    private static SystemMonitor SysMon = new
    SystemMonitor();
    // some stuff removed for clarity
    public static SystemMonitor getInstance()
    return SysMon;
    I say "why bother with that static method?".

  • Static class reference

    Below we have a class containing a static class variable and a static accessor method.
    The method is responsible for assigning the variable, which it does on demand.
    public class MyClass
        private static int INFO = -1;
        public static int getInfo()
            if(INFO < 0)
                try
                    INFO = ...;
                catch(Exception e)
            return INFO;
        }When using this class is it not safe to assume that the assignment of the variable will ever only occur once for the life of the system that uses this class? (afterall is it static within the class)
    I am experiencing the situation whereby EVERY time the method is called, the assignment of the variable is necessary. I can only assume that the static instance of this class in memory has been lost between each call and therefore the state/value of the variable has also been lost.
    It is worth noting that no object instances of this class are ever created. The class is accessed only through its static interface. It seems that since no local reference to objects of this class are held in memory then the entire class, along with its internal static state, is cleared from memory (garbage collected?).
    How is it possible to ensure that the state of static fields within such a class is preserved over time, without create instances of the class.
    John

    When using this class is it not safe to assume that
    the assignment of the variable will ever only occur
    once for the life of the system that uses this class?First of all, you haven't said what you assign it to, so we can't say. If you assign a value less than zero then it will be reassigned next time the method is called.
    Secondly, it depends on whether or not you're expecting it to be thread-safe? It isn't.
    If your code is not multi-threaded, then the section of code in your getInfo method that assigns the field should only execute once during a single run of an application.
    Thirdly, you explicitly assign it (to minus one) at class initialisation time, so stricty speaking, the variale will always be assigned at least once, and will be assigned at least once more if the getInfo method is ever called.
    I am experiencing the situation whereby EVERY time the
    method is called, the assignment of the variable is
    necessary. Can you offer any evidence to this? A small, complete, compilable and executable example that demonstrates the problem will help, and will probably get you an answer pretty quickly around here.
    I can only assume that the static instance
    of this class in memory has been lost between each
    call and therefore the state/value of the variable has
    also been lost.Then either there is a bug in your JVM, or at least two versions of the class have been loaded, and at least one of those was not loaded by the system classloader. Without further info, we aren't going to be able to help much more here.
    The class is accessed only
    through its static interface. It seems that since no
    local reference to objects of this class are held in
    memory then the entire class, along with its internal
    static state, is cleared from memory (garbage
    collected?).This is not allowed under the JLS if the class was loaded by the system classloader. If it was loaded by another classloader, then it is only allowed if it can be determined that the class will never again be used throughout the entire run of the application. Since you are referencing the class again, this should not be happening.
    How is it possible to ensure that the state of static
    fields within such a class is preserved over time,
    without create instances of the class.From what you have told us so far, it should be. You will probably have to provide some code for us to help you further.

  • Static Class Function vs. Instance Variables

    I'm making a Wheel class to spin the wheels on some toy
    trains as they move back and forth.
    Each wheel on the train is an instance of the Wheel class and
    there are several of them.
    I thought it would be great to just have a static class
    function to tell all the Wheels to start turning:
    Wheel.go();
    The Wheel class keeps a static array of all of its instances
    so I thought I would just loop through all of those instances and
    issue the wheelInstance.roll() method.
    So far it all works. But I was planning to use a setInterval
    to call the roll() method and each instance has its own rollID
    property that I would like to assign the setInterval ID to. Here is
    the problem.
    Since the rollID is an instance property I can't access them
    from a static class function. Is there any way to do this?
    Currently I"m just using an onEnterFrame which doesn't require me
    to use the instance properties.

    Technically yes, realistically for this class no.A
    class will probably take several hundred bytes at
    least to load, with no data of your own. So adding4
    bytes for a int is less than 1% of the total size.
    And if you are loading millions of differentclasses
    then you should rethink your design.If you don't instantiate the class when you reference
    a static variable why would you consume memory for the
    class other than the variable itself? I don't
    understand what you are talking about with the
    "millions of different classes", it's not germane to
    the question. Bottom line, referencing a static
    variable more than once will save memory.Using a class, static or by instance, requires that the class be loaded. A loaded class creates, at the very least, an instance of java.lang.Class. Any static members of the class are in addition to the storage space needed for the instance of java.lang.Class and for any internal storage needed by the JVM in addition to that.
    Thus if one has a static data member when the class is used in any way, the static data member takes storage space. However a member (non-static) does not take storage space.
    Of course the meta data for the member could take as much space as the static member so the point could be moot. Is that what you were referring to?

  • Convertion of class variable (static) into instance variable(non-static)!

    Dear all,
    got a slight different question.
    Is that possible to convert class variable (static) into instance variable(non-static)?
    If so, how to make the conversion?
    Appreciating your replies :)
    Take care all,
    Leslie V
    http://www.googlestepper.blogspot.com
    http://www.scrollnroll.blogspot.com

    JavaDriver wrote:
    Anything TBD w.r.to pass by value/reference (without removing 'static' keyword)?Besides the use of acronyms in ways that don't make much sense there are two other large problems with this "sentence".
    1) Java NEVER passes by reference. ALWAYS pass by value.
    2) How parameters are passed has exactly zero to do with static.
    Which all means you have a fundamentally broken understanding of how Java works at all.
    Am I asking something apart from this?
    Thanks for your reply!
    Leslie VWhat you're asking is where to find the tutorials because you're lost. Okay. Here you go [http://java.sun.com/docs/books/tutorial/java/index.html]
    And also for the love of god read this [http://www.javaranch.com/campfire/StoryPassBy.jsp] There is NO excuse for not knowing pass-by in Java in this day and age other than sheer laziness.

  • Class variables x static ones

    I am with a doubt. I would like that the variables I have in the c program behave as class variables and it do not occur, tghey behaves more like static variables. By any chance any one knows if its possible that the c internal variables behave like class variables?
    I am putting down the helloworld example and the output.
    --------- HelloWorld.c -----------------------------
    #include <jni.h>
    #include "HelloWorld.h"
    #include <stdio.h>
    int test = 0;
    JNIEXPORT void JNICALL
    Java_HelloWorld_hello(JNIEnv *env, jobject obj) {
    printf("Hello world! %d\n", test++);
    return;
    ------HelloWorld.java------------
    public class HelloWorld {
    public native void hello();
    static {
    System.loadLibrary("hello");
    public static void main(String[] args) {
    HelloWorld hw = new HelloWorld();
    hw.hello();
    hw.hello();
    hw = null;
    HelloWorld hw2 = new HelloWorld();
    System.out.println("-----------");
    hw2.hello();
    hw2.hello();
    ---------- output-----
    /testeHello @varda : java HelloWorld
    Hello world! 0
    Hello world! 1
    Hello world! 2
    Hello world! 3
    ---- I would like it was.....
    /testeHello @varda : java HelloWorld
    Hello world! 0
    Hello world! 1
    Hello world! 0
    Hello world! 1

    Thanks. I thought in let the variables I need in the Java class... However I think it would not work, I have some pretty complex structures in C that I would need to port to java, without to say I have some sockets and pointers also. First I really don't know if it is feasible, and second even if it is feasible It would be a lot of work, I know I am lazy :). The problem is that some of these need to be global, I really can't do in other way.
    Actually what I am doing is exactly create a vector to each global variable I need and I am also putting an ID at the Java class. In this way the C method know who is calling it and uses the id as index of the vector. Well It works, but I think it is pretty ugly (we call this kind of thing as "Hammer" :) and I would like to use some thing better ;).

  • Static classes and variables

    Hello,
    I put all of my constants in an *{color:#3366ff}interface{color}* called Constants.java (I only put constants in this file) and when obfuscated the Constants.class file is removed from .jar and constants are inlined into classes this is Great! However, do I gain anything by placing all of my static methods into one class? Currently, there are all over the place and also I have classes that are already static like HttpMgr.java/ErrorMgr.java/InfoMgr.java I am thinking about merging these classes together with all static methods defined within the project. Do I gain or loss anything by doing this?
    Thanks!

    you will gain some bytes by merging all the static classes in one.
    you can create a ManagerTool.java class and write inside all the static methods ...

  • Assign a value to class variable

    I want to define a class variable in class. And I want all subclasses of that class ot have a different value for that class variable. How can I do that?
    public class BaseClass {
      public static String tableName = "";
    }Now if I have a ClassA and I want to assign a value like this :
    public class ClassA extends BaseClass {
      tableName = "location";
    } I got an error message.
    I can move it in a static initializer block but then it will only work when the class is loaded. In my case its possible i want to get this value without loading the class.
    Ditto if i move it to constructor.
    Any input? Thanks

    Are you saying that if i have 2 classes ClassA and
    ClassB inherited from BaseClass, then both are
    sharing the same copy of 'tableName' staticvariable?
    If yes then I should go with an instance variable.No, I am saying that you can easily declare a
    tablName in A and another tableName in B.
    A.tableName will be shared between all the instances
    s of A. B.tableName will be shared between all the
    instances of B. And BaseClass.tableName is
    irelevant. I think you try to use
    BaseClass.tableName as some kind of template for
    sub-classes, but this does not happen: you need to
    declare tableName again and again in each subclass.
    IThanks for clarifying. Each class needs to have a variable "tableName" and it needs to have one copy of this variable for all of that class's objects. 2 classes will not have the same value of this tableName variable.
    Thats why I was defining it as static variable. And I define it in BaseClass so that I dont have to define it again in each subclass.
    Is there any better way? Thanks

  • How to access the parent class variable or object in java

    Hi Gurus,
    I encounter an issue when try to refer to parent class variable or object instance in java.
    The issue is when the child class reside in different location from the parent class as shown below.
    - ClassA and ClassB are reside in xxx.oracle.apps.inv.mo.server;
    - Derived is reside in xxx.oracle.apps.inv.mo.server.test;
    Let say ClassA and ClassB are the base / seeded class and can not be modified. How can i refer to the variable or object instance of ClassA and ClassB inside Derived class.
    package xxx.oracle.apps.inv.mo.server;
    public class ClassA {
        public int i=10;
    package xxx.oracle.apps.inv.mo.server;
    public class ClassB extends ClassA{
        int i=20;   
    package xxx.oracle.apps.inv.mo.server.test;
    import xxx.oracle.apps.inv.mo.server.ClassA;
    import xxx.oracle.apps.inv.mo.server.ClassB;
    public class Derived extends ClassB {
        int i=30;
        public Derived() {
           System.out.println(this.i);                  // this will print 30
           System.out.println(((ClassB)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassB
           System.out.println(((ClassA)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassA
        public static void main(String[] args) { 
            Derived d = new Derived(); 
    Many thanks in advance,
    Fendy

    Hi ,
    You cannot  access the controller attribute instead create an instance of the controller class and access the attribute in the set method
    OR create a static method X in the controller class and store the value in that method. and you can access the attribute by 
    Call method class=>X
    OR if the attribute is static you can access by classname=>attribute.
    Regards,
    Gangadhar.S
    Edited by: gangadhar rao on Mar 10, 2011 6:56 AM

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • JDEVELOPER 10G, ADF BC: Passivate static instance variables in AM?

    I understand the need to passivate/activate instance variables but what about static instance variables within an application module?
    Thanks,
    Wes

    Static variables - being class variables and not instance variables - persist without a need for passivation. Is there a particular reason or scenario why to use static variables? You have to consider that since all AM instances will share it, changing it in one AM instance - i.e. one user session - will affect all other AM instances - i.e. all other user sessions! You also have to consider the implications of multithreading when attempting to modify the static variable.

  • Usage of non static members in a static class

    Can you explain the usage of nonstatic members in a static class?

    Skydev2u wrote:
    I just recently started learning Java so I probably know less than you do. But from what I've learned so far a static class is a class that you can only have one instance of, like the main method. As far as non static members in a static class I think it allows the user to modify some content of the class(variables) even though the class is static. A quick Google help should help though.Actually the idea behind a static class is that you dont have any instances of it at all, its more of a place holder for things that dont have anywhere to live.
    Non-static members in a static class wouldnt have much use

  • Problems using a static class extending JSPDynPage

    When I use the pdk with netweaver for creating a new portal object and I want to create a new PortalComponent (JSPDynpage) the pdk generates me the next code:
    public class TestJspDynPage extends PageProcessorComponent {
      public DynPage getPage(){
          return new TestJspDynPageDynPage(); }
      public <b>static</b> class TestJspDynPageDynPage extends JSPDynPage{
        public void doInitialization(){ }
        public void doProcessAfterInput() throws PageException {}
        public void doProcessBeforeOutput() throws PageException {}
    Is there any reason for creating the new class that extends JSPDynPage static ?
    Regards.

    Hi,
    That is a common problem, all variables in your JSPDynPage, should be saved in IPortalComponentSession/HttpSession instead of having instance/class variables.
    http://help.sap.com/saphelp_nw70/helpdata/en/fc/f28f414141a709e10000000a155106/frameset.htm
    http://help.sap.com/saphelp_nw70/helpdata/en/a0/3b7f41009d020de10000000a1550b0/frameset.htm
    Greetings,
    Praveen Gudapati

  • Can we create static class in actionscript 3.0

    Hi If yes please send me chunk of code .
    thanks

    Hi Prashanth,
    There is no specifically a Static class in Flex that you can declare it at the compile time. However you can have Static variables and methods in your class and you can call them using the class name itself without creating an instance of that class.
    Here is the chunk of code...
    package com.constants
    [Bindable]
    public class ConsumerMessageConstants
      public static const UNABLE_TO_ENROLL_PLANS_MESSAGE_ID:String = "10000";
      public static const MARITAL_STATUS_UPDATED_MESSAGE_ID:String = "10001";
      public static const ERROR_IN_EDITING_MARITALSTAUS_MESSAGE_ID:String = "10002";
      public static const SMOKER_STATUS_SAVED_SUCCESSFULLY_MESSAGE_ID:String = "10003";
      public static const PASSWORD_RESET_REQUIRED_MESSAGE_ID:String = "10004";
      public static const ADDRESS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10005";
      public static const UNABLE_TO_REMOVE_THIS_DEPENDENT_MESSAGE_ID:String = "10006";
      public static const EMPLOYEE_SALARY_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10007";
      public static const ERROR_IN_EDITING_SALARY_MESSAGE_ID:String = "10008";
      public static const PLEASE_SELECT_A_CONSIDER_PLAN_MESSAGE_ID:String = "10009";
      public static const YOU_MUST_CHOOSE_A_PLAN_COVERAGE_LEVEL_MESSAGE_ID:String = "10010";
      public static const PLEASE_SELECT_PLAN_TO_LOCK_PORTFOLIO_MESSAGE_ID:String = "10011";
      public static const DEEPDIVE_INFORMATION_SAVED_SUCCESSFULLY_MESSAGE_ID:String = "10012";
      public static const NO_DATA_TO_DISPLAY_MESSAGE_ID:String = "10013";
      public static const NO_PLANS_AVAILABLE_TO_ENROLL_MESSAGE_ID:String = "10014";
      public static const NO_PLANS_TO_BE_ENROLLED_MESSAGE_ID:String = "10015";
      public static const PASSWORD_CHANGED_SUCCESSFULLY_MESSAGE_ID:String = "10016";
      public static const NEW_PASSWORD_AND_CONFIRM_PASSWORD_SAME_MESSAGE_ID:String = "10017";
      public static const YOUR_DATA_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10018";
      public static const HEALTH_PLAN_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10019";
      public static const HEALTH_PLAN_IS_ADDED_SUCCESSFULLY_MESSAGE_ID:String = "10020";
      public static const MONEY_PLAN_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10021";
      public static const MONEY_PLAN_IS_ADDED_SUCCESSFULLY_MESSAGE_ID:String = "10022";
      public static const PROTECTION_PLAN_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10023";
      public static const PROTECTION_PLAN_IS_ADDED_SUCCESSFULLY_MESSAGE_ID:String = "10024";
      public static const UNABLE_TO_RETRIEVE_PATHS_MESSAGE_ID:String = "10025";
      public static function func1():Void
      public static function func2():Void
      public function ConsumerMessageConstants()

  • Maybe you are looking for

    • Early 2009 24" iMac Haywire Display: LCD Panel or Logic Board?

      Hi, My 24" display just developed severe vertical and horzontal lines, mouse trailing, color changing and flickering.  The problem begins as soon as the computer is turned on (even the Apple screen goes nuts). When I plug in an external display, the

    • After Effects & Effects Plugins

      On the verge of getting After Effects. I am going to d/load the trial but i wanted to ask this first. Have been looking at various tutorials on the CreativeCow site for some things that i want to use After FX for. There a lots of effects that have th

    • Invoking MS Excel from Java

      HI, I'm trying to create a standalone application that would need to logon in a database.If the user is a valid one, the user can then choose which table he wanted to update. All the rows of the column will be shown in an excel format. (the program w

    • Compile error with BufferedImage (sorta)

      I complied my program and got this error from JavaC: C:\mydocu~1\visual~1\checke~1\checkersLabel.java:76: cannot resolve symbolsymbol  : method dBufferedImage  (java.awt.image.BufferedImage)location: class checkersLabel                dBufferedImage(

    • Transaction monitoring in Oracle

      Hi. I don't know if this is the right forum, but here goes: We've developed a system, where all the client transactions gets processed by our own backend, as well as the database. Like in: Client: begin trans insert into t1 ... insert into t2 update