345

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?

0

7 Answers 7

382

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.

10
  • 12
    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, 2013 at 9:59
  • 71
    @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. Jul 19, 2013 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? Aug 28, 2013 at 19:31
  • 61
    the order of execution is: static initializer, instance initializer, constructor Feb 19, 2014 at 0: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, 2014 at 8:34
109

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.

8
  • @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. Aug 28, 2013 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, 2013 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. Oct 31, 2013 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 7, 2015 at 12:55
  • 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, 2018 at 19:01
75

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() {

    }
}
3
  • 1
    This looks like a normal constructor. Jun 14, 2015 at 15:08
  • 14
    @DerGolem I think he's referring to the braces above the normal constructor.
    – Saad
    Jun 28, 2015 at 16:55
  • 6
    Didn't even notice that... ;) Yes, weird! Jun 28, 2015 at 16:57
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); 
    }
}
1
  • 7
    this is only true until version 7 where you are obligated to write a main if you want to run the code.
    – XFCC
    Dec 4, 2014 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.

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
  • Your link is unavailable
    – Ori Marko
    Oct 4, 2018 at 8:50
  • @user7294900 Check this link
    – SGK
    Oct 25, 2018 at 19:00
-4

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.

2
  • 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, 2015 at 20:27
  • static block works in all versions of Java. I am using Java 14 and it works correctly. Oct 30, 2021 at 8:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.