Printing message on Console without using main() method

后端 未结 10 1758
情歌与酒
情歌与酒 2020-11-27 03:04

I was asked this question in an interview.

How to print message on console without using main() method?

10条回答
  •  粉色の甜心
    2020-11-27 03:17

    public class Foo {
        static {
             System.out.println("Message");
             System.exit(0);
        } 
    }
    

    The System.exit(0) exits program before the jvm starts to look for main()

    (Note: This works only with java 6. Even if it compiles with JDK 7's javac it cannot be run with its java, because it expects a main(String[]) method.)

提交回复
热议问题