0

Look at the code

public class Sample {

    public static void main(String[] args) {
        Cache.load();
        System.out.println(Cache.get());
    }

}
class Cache {
    static List<String> l = new ArrayList<String>();

    public static List<String> get() {
        return l;
    }

    public static void load() {
        l.add("shiva");
        l.add("rachakonda");
    }
}

When Cache.load() is called array list object is initialized and after calling Cache.get(), it is able to give list elements. How the arrayList data is still available? I've expected the output as empty list.

Siva R
  • 427
  • 2
  • 8
  • 23
  • Why do you expect that? – Oliver Charlesworth Jun 25 '17 at 14:16
  • 1
    I fail to understand your reasoning. You add two elements to a list, then get that list, and expect the list to be empty. Why would it be empty, since you just added two elements to it? – JB Nizet Jun 25 '17 at 14:17
  • 1
    @JBNizet I suspect the confusion surrounds the behavior of `static` when applied to class variables. The OP might not understand that the list "sticks" across calls because it is static. – Tim Biegeleisen Jun 25 '17 at 14:18
  • @JB Nizet After Cache.load() nothing is referred to that list. Isn't it garbage collected? – Siva R Jun 25 '17 at 14:21
  • 2
    Yes, The Cache class, which is loaded and kept in memory, refers to it. That's the whole principle of static members. A class is not reloaded and reinitialized every time you call a method on it. It's loaded and initialized once, and then stays in memory. – JB Nizet Jun 25 '17 at 14:22
  • The list is initialized with the declaration, not the `load` call. It's added to by `load`, but it already existed. – Lew Bloch Jun 25 '17 at 14:37

0 Answers0