Java Basics: static functions without names or return types

public class Main {
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 want to know what this nameless static function is

I've never seen anything like this in Java (I'm currently learning)

What is it for?

When is it usually used?

When will it be executed in the program?

Solution

This is called a static block and is executed only once during initialization In addition, if there are multiple static initialization blocks, the runtime ensures that they are called in the order they appear in the source code

This is a good explanation with some sample code a https://www.geeksforgeeks.org/g-fact-79/

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>