42

I came across this Java code:

static {
    String aux = "value";
    try {
        // some code here
    } catch (Exception e) { }
    String UUID_prefix = aux + ":";
}

I am new to Java, please explain what is happening here.

Beth Lang
  • 1,889
  • 17
  • 38
sufyan siddique
  • 1,461
  • 4
  • 13
  • 14

7 Answers7

47

This is a static initialization block. Think of it like a static version of the constructor. Constructors are run when the class is instantiated; static initialization blocks get run when the class gets loaded.

You can use them for something like this (obviously fabricated code):

private static int myInt;

static {
    MyResource myResource = new MyResource();
    myInt = myResource.getIntegerValue();
    myResource.close();
}

See the "Static Initialization Blocks" section of Oracle's tutorial on initializing fields.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
12

This is the block of code that will get invoked when your class is loaded by classloader

jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    Thanks Joshi. Actually, i want to translate this code to C++. Could you explain how can i do this? – sufyan siddique Nov 10 '11 at 16:09
  • 1
    @sufyansiddique: You should come up with a new question. – Bhesh Gurung Nov 10 '11 at 16:14
  • WHat is there in C++ that gets executed when class is loaded just put the block of code there simply – jmj Nov 10 '11 at 16:15
  • Write a function for your class and add a a static `bool inited` field. Call the function from your ctor only if `inited` is false. Set it to true after the first call. – zeller Nov 10 '11 at 16:15
7

This is a static initializer block. You must have found it in a class's body outside of any method. The static init block runs only once for each class, at classload time.

zeller
  • 4,904
  • 2
  • 22
  • 40
4

This is a static initializer.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
3

Sufyan,

Static initializers aren't inherited and are only executed once when the class is loaded and initialized by the JRE. That means this static block will be initialized only once irrespective of how many objects you have created out of this class.

I am not a big fan of it and i am sure there are better alternatives for it depending on the situation.

Thanks, Reds

skusunam
  • 411
  • 3
  • 12
2

This is called a static initialization block and will be executed once, when this class gets loaded.

reef
  • 1,813
  • 2
  • 23
  • 36
0

This syntax has been outdated as of Java 7. Now the equivalent is:

public static void main(String[] args) {
    /*
      stuff
    */
}
Dime
  • 9
  • 1