Search code examples
javaandroidstaticstatic-block

Android:I do not understand: static { foo();}


Sometimes I see something like it, in a class in Android:

static
{
    foo();
}
  • What does this do?

  • Why?


Solution

  • That's a static block. It is executed the first time that class is referenced on your code, and it is calling a static method called foo(). You can find more about the static block here. As mentioned by @CommonsWare, you can initialize a static field in two different ways, inline a declaration time

    static ArrayList<String> test = new ArrayList<String>() {{
        add("A");
        add("B");
        add("C");
    }};
    

    but as you can see it is not easy to read. If you use a static block instead

      static ArrayList<String> test;
      static {
            test = new ArrayList<>();
            test.add("a");
            test.add("b");
            test.add("c");
        } 
    

    or as in your question have

    static ArrayList<String> test;
    static {
      foo();
    }
    
    private static void foo() {
        test = new ArrayList<>();
        test.add("a");
        test.add("b");
        test.add("c");
    }