In the Java language, the main() method is the entry method of the program. When the program is running, the main() method is loaded first, but does this mean that the main() method is the first module to be executed when the program is running? Woolen cloth?
The answer is no. In the Java language, since the static block is called when the class is loaded, the static block can be used to output "Hello World" before the main() method is executed. Take the following code as an example.
package com.magic.main;
public class StaticMainDemo {
static {
System.out.println("Hello World!");
}
public static void main(String[] args) {
System.out.println("Hello, main method!");
}
}
Run StaticMainDemo , you can see the following output information:
Hello World!
Hello, main method!
Judging from the output, "Hello World!" is preferentially output before the main() method is executed. In the above example code, the static static code block is located before the main() method. If the position is changed, will the output result be the same?
package com.magic.main;
public class StaticMainDemo {
public static void main(String[] args) {
System.out.println("Hello, main method!");
}
static {
System.out.println("Hello World!");
}
}
Execute again, you can see that the output is the same
Hello World!
Hello, main method!
That is to say, no matter where the static code block is located, it is executed in preference to the main() method. As for why this is the case? This involves another knowledge point, which is the sequence of Java program initialization .
Since this article is mainly used to share about the main() method in Java, we will not discuss the sequence of Java program initialization. However, here is a post about [ What is the sequence of Java program initialization? ? ]'s answer analysis screenshot, as follows:
For more knowledge points related to Java interviews, you can pay attention to the [Java Interview Manual] applet, which involves Java foundation, multithreading, JVM, Spring, Spring Boot, Spring Cloud, Mybatis, Redis, database, data structure and algorithm.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。