325

I was looking over some code the other day and I came across:

static {
    ...
}

Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?

Mohit Deshpande
  • 48,747
  • 74
  • 187
  • 247

7 Answers7

362

It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).

It can be thought of as a "class constructor".

Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.

Hearen
  • 6,019
  • 2
  • 36
  • 50
Joachim Sauer
  • 278,207
  • 54
  • 523
  • 586
  • 11
    So why would you use a non-static instance initializers and not simply make use of the class constructor (I can think of this being useful in anonymous classes)? – Jori Jul 19 '13 at 09:59
  • 67
    @Jori: a common reason is if you have multiple separate constructors (that *don't* just "redirect" to a single canonical one) and you want all of those to have some initialization in common. – Joachim Sauer Jul 19 '13 at 10:10
  • 3
    Makes the code clearer and less repetitive. The folks that make Java specifications sometimes make things more confusing, but almost always there is a underlying reason to why they did it that way. Stream manipulation, anyone? – Mindwin Aug 28 '13 at 19:31
  • 56
    the order of execution is: static initializer, instance initializer, constructor – Someone Somewhere Feb 19 '14 at 00:46
  • 2
    @SomeoneSomewhere While "instance initializer, constructor" follow each other, the "static initializer" may have been executed long before. But you are right, the order is that, initially. Indeed, it is "SI, II, C, II, C, II, C, ...". – glglgl Aug 31 '14 at 08:34
  • @JoachimSauer Can you please elaborate on "class is loaded". What does it mean? Instantiating it? Cause I've found that static block isn't being executed unless I instantiate the class. – Quazi Irfan Jan 24 '15 at 22:56
  • @iamcreasy: [This](http://www.programcreek.com/2013/01/when-and-how-a-java-class-is-loaded-and-initialized/) is the first hit when searching for "class is loaded" ;-) – Joachim Sauer Feb 02 '15 at 14:23
  • @Midwin I saw a static block calling a function which registered some streams. What is it? – sudeepdino008 Jul 08 '16 at 12:07
  • Is the static block only called only once? – JaskeyLam Oct 31 '16 at 02:51
  • @Jaskeyn once when the class is initiallized, yes. A class could be loaded/initiallized multiple times in some specific situations, which would run the static block multiple times. But for the JVM those then constitute different classes (even if they have the same name). – Joachim Sauer Oct 31 '16 at 09:42
104

It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.

From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

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.

If you have a class with a static look-up map it could look like this

class MyClass {
    static Map<Double, String> labels;
    static {
        labels = new HashMap<Double, String>();
        labels.put(5.5, "five and a half");
        labels.put(7.1, "seven point 1");
    }
    //...
}

It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.

aioobe
  • 383,660
  • 99
  • 774
  • 796
  • @aioobe I understand that it might not be necessary, but one will never learn of static initializers without being exposed to them. Also, in some cases class member initialization in the declaration is disencouraged (some companies I worked for), and initializing them inside static block or in the constructor (for non-static members) was the recommended practice. – Mindwin Aug 28 '13 at 19:29
  • 1
    I see. Why is it discouraged? Personally I find member initialization at the declaration quite easy to read and maintain. I would argue that forcing them into the constructors may a bad idea, especially if you have more than one constructor and need to repeat the initialization. (If you for instance change from ArrayList to LinkedList you need to remember to change it in multiple places.) – aioobe Aug 28 '13 at 20:18
  • As you said, we need to repeat the initialization code in every constructor. It would be best, if we initialize them in the instance initializers. – JavaTechnical Oct 31 '13 at 10:15
  • 1
    "The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code." the code in he static block must be executed first of all even before the constructor of the class – Arno Aug 07 '15 at 12:55
  • @aioobe, what if I directly put `labels.put(...)` instead of wrapping that inside `static {}`? – CodeYogi Sep 10 '15 at 06:27
  • First of all, `labels.put(...)` is a statement, and you can't put statements directly in the class body. You *can* put them in the constructor, but then they would run each time a new `MyClass` object is created. By putting them in `static { ... }` you make sure these `put`-statements are executed once, when the class is loaded. (If this didn't answer your question, could you please post a snippet that explains what you suggest.) – aioobe Sep 10 '15 at 07:12
  • You make no sense why you would write that code. – Philip Rego Feb 15 '18 at 18:14
  • 1
    @PhilipRego, static initializer can be useful in certain situations. In an anonymous class for example, there's no constructor to put instance initialization in. – aioobe Feb 15 '18 at 19:01
74

It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.

It is also possible to write non-static initializers, which look even stranger:

public class Foo {
    {
        // This code will be executed before every constructor
        // but after the call to super()
    }

    Foo() {

    }
}
NobleUplift
  • 4,577
  • 6
  • 37
  • 76
Simon Lehmann
  • 9,924
  • 4
  • 39
  • 52
17

Static block can be used to show that a program can run without main function also.

//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
    static
    {
        System.out.println("Welcome to Java"); 
        System.exit(0); 
    }
}
Yu Hao
  • 111,229
  • 40
  • 211
  • 267
user3777803
  • 171
  • 1
  • 2
  • 6
    this is only true until version 7 where you are obligated to write a main if you want to run the code. – XFCC Dec 04 '14 at 15:02
6

A static block executes once in the life cycle of any program, another property of static block is that it executes before the main method.

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
Zahid Hussain
  • 61
  • 1
  • 2
3

Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation. http://www.jusfortechies.com/java/core-java/static-blocks.php

-2

yes, static block is used for initialize the code and it will load at the time JVM start for execution.

static block is used in previous versions of java but in latest version it doesn't work.

Piyush
  • 1
  • 1
  • 2
    not when JVM starts but when the class is loaded. JVM uses a class loading mechanism so it loads the class when it is used, not before and never when the JVM starts – 4lberto May 26 '15 at 20:27