关于java:Java面试手册基础篇能否在Java中终止main方法

答案是必定的,能够应用 System.exit() 办法终结 main() 办法

示例代码如下:

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");
    }
    
}    

运行 MainDemo 类,输入的后果如下:

Hello World

Process finished with exit code 0

从输入后果能够看出,main() 办法被终止了,并没有打印出 “Main End”。

应用 System.exit(0) 是退出了整个虚拟机,之后的语句都不会被再执行了,上面来验证一下加上 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");
        }
    }
    
}   

运行程序,输入后果如下:

Hello World

Process finished with exit code 0

尽管有 finally ,然而外面的语句并不会被执行。

更多无关Java面试相干的知识点能够关注【Java面试手册】小程序,波及Java根底、多线程、JVM、Spring、Spring Boot、Spring Cloud、Mybatis、Redis、数据库、数据结构与算法等。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理