Updating static variables in java

I have a class with static variables:

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

And if I try to change the DOMAIN from the activity of Android (or another java class) at runtime, the DOMAIN variable will change, but PRIVATE_AREA will not change. What for?

+6
source share
4 answers

This is because static fields are assigned after the class is loaded (only happens once) in the JVM. The PRIVATE_AREA variable PRIVATE_AREA not be updated when the DOMAIN variable changes.

 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 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 } } 
+6
source

This is because static variables are initialized only once, at the start of execution.

See more at: http://www.guru99.com/java-static-variable-methods.html

+2
source

PRIVATE_AREA has not changed because it is set at the time of announcement. When you change DOMAIN, it does not affect PRIVATE_AREA. It might be better to work with the setter (...) and getter () methods and local variables. Upon receipt of PRIVATE_AREA, re-create the reuse value again.

0
source

The assignment of a variable occurs during class loading, so after that, if you change the value of one static variable, it will not reflect where it is assigned to another variable

0
source

Source: https://habr.com/ru/post/988312/


All Articles