0

I'm unsure what this does, I haven't seen it before and can't find any information about it.

private static String[] names = { "A.ttf" };

private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);

static {
  for (String name : names) {
    cache.put(name, getFont(name));
  }
}
Zong
  • 6,160
  • 5
  • 32
  • 46
juju
  • 553
  • 1
  • 4
  • 21
  • 1
    It's a [static initializer](http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html). You can use it to initialize static fields. – Zong Nov 28 '13 at 18:10

2 Answers2

5

That is not a static method but a static block.

Static blocks are executed first(in same order they are declared) when class gets loaded and usually used for initializing things.

in your case it puts all names in "names" to cache.

refer this or an answer on SO for more info

Community
  • 1
  • 1
dev2d
  • 4,245
  • 3
  • 31
  • 54
1
  1. A block is denoted by {\\some code}. A placed static keyword denotes that it is a static block. static block is known as Static Initializers and non static block is known as Instance Initializers.

  2. None of them can contain return statement.

  3. The non-static block will be called every time you are creating a new instance and it will be called/executed just before the Constructor. The static block will be called/executed only once and it will be the first time your are accessing the class.

Example:

  class A {  
     static{  // static
       System.out.println("Static block of Class A");  
     }  

     { // non-static  
       System.out.println("Non-Static block of a instance of Class A");  
     }  
  public A(){  
    System.out.println("Constructing object of type A");  
  }  
}  

public class StaticTest {  
  public static void main(String[] args) {  
    A a1 = new A();  
    A a2 = new A();  

  }  
}  

Output:

static block of Class A
Non-Static block of a instance of Class A
Constructing object of type A
Non-Static block of a instance of Class A
Constructing object of type A
Sage
  • 15,290
  • 3
  • 33
  • 38