7

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?

Lucifer
  • 29,392
  • 25
  • 90
  • 143
AlexBerry
  • 103
  • 1
  • 1
  • 6
  • Do not introduce mutable static variables - that is one of the worst anti-patters in java introducing entropy and maintainability issues – rgasiore Jun 01 '15 at 12:06

4 Answers4

8

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
    }
}
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
2

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

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

Wald
  • 1,063
  • 7
  • 13
1

PRIVATE_AREA did't change because it is set on declaration time. When You change DOMAIN, it has no effect on PRIVATE_AREA. Maybe it is better to work with setter(...) and getter() Methods and local variables. On getting PRIVATE_AREA You create the retrun value again.

Juergen-GH
  • 36
  • 3
0

Assignment of variable happens at the load time of class thats why after that if you change the value of one static variable, it will not reflect there where it is assigned to another variable

Amit Das
  • 1,077
  • 5
  • 17
  • 44