AlexBerry
AlexBerry

Reputation: 103

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?

Upvotes: 7

Views: 12970

Answers (4)

Amit Das
Amit Das

Reputation: 1107

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

Upvotes: 0

SamTebbs33
SamTebbs33

Reputation: 5647

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
    }
}

Upvotes: 8

Juergen-GH
Juergen-GH

Reputation: 36

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.

Upvotes: 1

Wald
Wald

Reputation: 1091

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

Upvotes: 2

Related Questions