Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update static variables in java

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?

like image 813
AlexBerry Avatar asked Jun 01 '15 11:06

AlexBerry


1 Answers

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
    }
}
like image 103
SamTebbs33 Avatar answered Sep 23 '22 01:09

SamTebbs33