user2113792
user2113792

Reputation: 75

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?

Upvotes: 4

Views: 379

Answers (1)

Ryan
Ryan

Reputation: 1974

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.

Upvotes: 6

Related Questions