If a class has a main method in it, and it is the class you want to run, then java always look inside the main
method to start executing.
For example in this case,
public class Test {
public static void main(String[] args) {
A a = new A();
a.method();
}
public static void method() {
System.out.println("method() in class Test");
}
}
class A {
public static void main(String[] args) {
Test.method();
}
public void method() {
System.out.println("method() in class A");
}
}
If I run Test.java, then main method of Test class will execute first and vice versa.
Now there is a way to make java run code before looking into main method of the class. Take a look at following code.
public class Test {
static {
A a = new A();
a.method();
}
public static void main(String[] args) {
System.out.println("main() of Test executing");
}
}
class A {
public void method() {
System.out.println("method() in class A");
}
}
The use of static{...}
in the class makes executing the code within static block first and then the main block. It is called the static initializer is a static {} block of code inside java class, and
run only one time before the constructor or main method is called.
It is a block of code static { ... } inside any java class, and executed by virtual machine when class is called.
- No return statements are supported.
- No arguments are supported.
-No this or super are supported.
Usually this can be used anywhere. But I see most of the time it is used when doing database connection, API init, Logging and etc.