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.


十方
226 声望433 粉丝