3

I've never seen this before - what is it called? This is a class level variable, at the beginning of the file.

Just to be clear, I'm referring to the static {} after the variable.

private static final UriMatcher URI_MATCHER;
    static {
        URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
        URI_MATCHER.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH);
        URI_MATCHER.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH);
        URI_MATCHER.addURI(AUTHORITY, "books", BOOKS);
        URI_MATCHER.addURI(AUTHORITY, "books/#", BOOK_ID);
    }
richarbernal
  • 1,063
  • 2
  • 14
  • 32
Cody
  • 8,686
  • 18
  • 71
  • 126

5 Answers5

4

It's an static initialization block. It can be declared anywhere inside a class (but outside a method), but by convention it's usually written right after the static variable that's being initialized. It's specified in the Java Language Specification, section §8.7.

As the name implies, it's normally used for initializing the state of static attributes in the class at class-loading time. From the Java tutorial:

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword (...) A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

that is used to initialize static variables. As you know, you cannot initialise them in constructor of your class, so you can use static block As an example: you want to fill static array with value 1, 2, 3 and so on. There is two ways:

public class Main {
    static int[] array1 = {1, 2, 3, 4 ...};

    static int[] array2;
    static {
        array2 = new int[N];
        for (int i = 0; i < N; i++) {
            array2[i] = i;
        }
    }
}
alaster
  • 3,821
  • 3
  • 24
  • 32
1

This is a static portion of code that initialices the static var URI_MATCHER after it's declared

richarbernal
  • 1,063
  • 2
  • 14
  • 32
0

It's a static initialization block. It allows you to "set up" your static fields, which cannot be done correctly in the methods of the class instances.

Bananeweizen
  • 21,797
  • 8
  • 68
  • 88
0

It's just a static initialization block. Check out: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html