are static variable in a class duplicated when a new instance of the class is created?

java, oop

Solution

No. Static variables are allocated once, when the class is initialized. From the Java Language Specification, §8.3.1.1 `static` fields:

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

Note that this refers to the field itself, not to any value the field may contain. Unless the field is declared `final`, you can assign values one after another to it. In particular, you can [mis]use constructors to assign a value to the field every time an instance is created. In general, you should avoid assigning to a static field in a constructor. (There are exceptions, such as using a static field to count instance object creations.)

You can access a static field using the class name or using a reference to an instance.1 Thus, the following are all equivalent (provided `foo` and `bar` are of type `EpicClass`):

EpicClass.arylst
foo.arylst
bar.arylst

(Accessing a static field via an instance reference is considered wrong and will usually generate a compiler warning, but it works perfectly well—even if the reference is `null`, because the compiler converts it to the first form.) In that sense only, the "stuff in the ArrayList" will appear to be duplicated in each instance of the class. However, there is only one instance of the `ArrayList` and you are just accessing it via (seemingly) different mechanisms.

1provided the field is accessible at all, of course.

Problem

Here there. Suppose i have this class ``` public class EpicClass{ public static ArrayList<String> arylst = new ArrayList<>(); public String field1; public String field2: } ``` Now if I execute this code: ``` /* ... Code which adds stuff to arylst ... */ EpicClass foo = new EpicClass(); EpicClass bar = new EpicClass(); ``` Will the stuff in the ArrayList be duplicated in `foo` and `bar`??

Original source