Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 302
Itako Avatar asked Apr 12 '11 12:04

Itako


People also ask

Does a static method need a return type?

it is a method accessible from outside the class where it is defined (public), it is a static method (static), it does not return any result (return type is void), and. it has a parameter of type array of strings (see Unit 7).

Can we call static method without class name?

Yes you can call a static method without the class name.

Can static method have return type in Java?

In Java, a static method may use the keyword void as its return type, to indicate that it has no return value.

What is a static function in Java?

A static method in Java is a method that is part of a class rather than an instance of that class. Every instance of a class has access to the method. Static methods have access to class variables (static variables) without using the class's object (instance). Only static data may be accessed by a static method.


1 Answers

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/

like image 54
John Kane Avatar answered Nov 15 '22 08:11

John Kane