The answer is yes, you can use the System.exit() method to terminate the main() method .
The sample code is as follows:
package com.magic.main;
public class MainDemo {
public static void main(String[] args) {
System.out.println("Hello World");
System.exit(0);
System.out.println("Main End");
}
}
Run the MainDemo class and the output is as follows:
Hello World
Process finished with exit code 0
As you can see from the output, the main() method is terminated and "Main End" is not printed.
Use System.exit(0) to exit the entire virtual machine, and the subsequent statements will not be executed again. Let's verify the case of adding finally:
package com.magic.main;
public class MainDemo {
public static void main(String[] args) {
System.out.println("Hello World");
try {
System.exit(0);
} finally {
System.out.println("Main End");
}
}
}
Run the program and the output is as follows:
Hello World
Process finished with exit code 0
Although there is finally, the statement inside will not be executed.
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) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。