简体   繁体   中英

Static variable in class java

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM