Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java no name static method

What is this?

public class ABC {    public ABC() {          System.out.println("world");    }    static {          System.out.println("hello");    } } 

Will print: hello world

I don't really understand this, or what kind of method that static code is.

like image 369
AEIOU Avatar asked Dec 02 '09 22:12

AEIOU


People also ask

What is static method without name in Java?

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.

Can static and non static method have same name?

A static and non static method can't have the same signature in the same class . This is because you can access both a static and non static method using a reference and the compiler will not be able to decide whether you mean to call the static method or the non static method.

Can we call non static method from static method in Java?

“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.

Can we call static method without object in Java?

1. The instance method requires the object of its class to be created before it can be called. Static methods in Java can be called without creating the object of the class.


2 Answers

It's called a "static initialisation block".

It runs when the class is first loaded; only once.

For example, a constructor will run each time the class is instantiated; the static block only runs once, when it's first loaded statically by the VM/Class loader.

like image 81
Noon Silk Avatar answered Oct 16 '22 06:10

Noon Silk


I think it's worth noting the static block will be run exactly once each time a classloader loads a class. This means if you have more than one classloader, the block can execute more than once.

like image 39
Romain Avatar answered Oct 16 '22 08:10

Romain