Search code examples
javastaticstatic-variables

Static Variable becomes null after class completed


I Have three classes

  1. StaticHolder.java - Which holds a static variable.
  2. StaticInitializer.java -Responsible only for initializing the variable through a static method.
  3. Application.java - Retrieves the static variables value through getter method.

I thought initializing a static variable once in JVM will not go until we stop the JVM. So I called ran StaticInitializer once which will do the initialization. And tired to access its value from another class which is not working and returning null. Can anyone explain why. Thanks In Advance.

public class StaticHolder {
    private static String hello;

    public static void ini() {
        hello = "Hello World";
    }

    public static String getHello() {
        return hello;
    }

    public static void setHello(String hello) {
        StaticHolder.hello = hello;
    }
}

class StaticInitializer {
    public static void main(String[] args) {
        StaticHolder.ini();
        while (true) {
            Thread.sleep(1000);
        }
    }
}

public class Application {
    public static void main(String[] args) {
        System.out.println(StaticHolder.getHello());
    }
}

Solution

  • static does not mean that this value is there forever!

    It is only theree for the current java session.

    Invocing the java command at the command line starts a new java session where the value needs to be initialized again.


    Actually I have a daemon thread which does the initialization and stays alive.And I have another stand alone java program which tries to get the value.

    Without knowing that other code involved my gueass is that you did not establish inter process communication.

    The easiest way it that you "deamon" opens a server socket and your "stand alone java program" connects to it an queries the desired data through it.