Search code examples
javafunctionstaticstatic-initializer

Java basics: a static function without a name, or return type


public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?


Solution

  • That is called a static block and will only be executed once during initialization. Also, if there are more than one static initialization blocks, the run time guarantees that they will be called in the order they appear in the source code.

    Here is a pretty good explanation with some example code a. https://www.geeksforgeeks.org/g-fact-79/