I want to ask if static variable in class will add extra memory the the initialized class.
Lets say I have a class like this:
public class Sample{
public static String NAME[] = {"1", "2", "3", "4"};
private int id;
private String uuid;
private String name;
public void setUuidString() {
UUID uuid = UUID.randomUUID();
this.uuid = uuid.toString();
}
public void setName(String name) {
this.name = name;
}
public void setCustomUuid(String uuid) {
this.uuid = uuid;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getUuid() {
return uuid;
}
public String getName() {
return name;
}
}
And I create Sample class multiple times initializing it and adding to an array of Sample class does the static variable adds extra memory the the class or will it only get only one memory location when it is static?
-
1@Abdelhak i would disagree, this is more about memory management questionRyan– Ryan2016年01月07日 17:44:31 +00:00Commented Jan 7, 2016 at 17:44
-
"I create Sample class" - post an example.Roman C– Roman C2016年01月07日 17:48:06 +00:00Commented Jan 7, 2016 at 17:48
1 Answer 1
Since static variables are initialized at the start of the programs execution, memory is set aside for the variable. Since the variable is static it belongs to its class not instances of the class. So for every instance you create it will not use extra memory.
With static variables a single instance of the variable is shared throughout all instances of the class, although you do not need a instance of the class to access the variable.
2 Comments
static variables are actually initialized when the class is first loaded, not program start. For example, the initialization-on-demand idiom takes advantage of this fact to ensure lazy, thread-safe loading of singletons