Update static variables in java

AlexBerry picture AlexBerry · Jun 1, 2015 · Viewed 7.8k times · Source

I have a class with static variables as:

 class Commons { 
public static String DOMAIN ="www.mydomain.com"; 
public static String PRIVATE_AREA = DOMAIN + "/area.php";
} 

And if I try to change DOMAIN from an Android Activity (or another java class) at runtime, the DOMAIN variable change but PRIVATE_AREA don't change. Why?

Answer

SamTebbs33 picture SamTebbs33 · Jun 1, 2015

This is because the assignment of static fields happens once the class is loaded (occurs only one time) into the JVM. The PRIVATE_AREA variable will not be updated when the DOMAIN variable is changed.

public class Test {
    public static String name = "Andrew";
    public static String fullName = name + " Barnes";
    public static void main(String[] args){
        name = "Barry";
        System.out.println(name); // Barry
        System.out.println(fullName); // Andrew Barnes
    }
}

I suggest that you use the following structure.

public class Test {
    private static String name = "Andrew";
    public static String fullName = name + " Barnes";

    public static void setName(String nameArg) {
        name = nameArg;
        fullName = nameArg + " Barnes";
    }

}

Test2.java

 public class Test2 {

    public static void main(String[] args){
        System.out.println(Test.fullName); // Andrew Barnes
        Test.setName("Barry");
        System.out.println(Test.fullName); // Barry Barnes
    }
}