1

I have encountered the following code:

public final class MainActivity extends ActivityBase

{

    static

    {
        Logger.create();      
    }
...

}

what does static area like this means?

What's the advantage using this syntax?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471
  • 1
    You didn't ask it here - but if you want to use the Logger in more than one Activity you could also initialize it in the Application class - then you don't have to do it several times. http://developer.android.com/reference/android/app/Application.html – Simon Meyer Jul 29 '13 at 22:06

3 Answers3

4

Official Documentation

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

 static {
     // whatever code is needed for initialization goes here }

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.

There is an alternative to static blocks — you can write a private

static method:

 class Whatever {
     public static varType myVar = initializeClassVariable();

     private static varType initializeClassVariable() {

         // initialization code goes here
     } 
 } 

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

Smit
  • 4,685
  • 1
  • 24
  • 28
amatellanes
  • 3,645
  • 2
  • 17
  • 19
2

Whenever the class is loaded (imported), the static block will execute. It's usually used to initialize static variables and whatnot.

Vyassa Baratham
  • 1,457
  • 12
  • 18
1

It is a static initializer. It allows one to initialize static variables (even static final) by using a set of statements instead of just an expression.

In this case, it performs an activity whenever the class is first referenced, even without creating an instance of the class.

rgettman
  • 176,041
  • 30
  • 275
  • 357