Printing message on Console without using main() method

后端 未结 10 1793
情歌与酒
情歌与酒 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:10

    class MainMethodNot
    {
        static
        {
            System.out.println("Hello World");
            System.exit(0);
    
        }
    }
    

    Because the static initializer block is executed when the class is first loaded, we can print out “Hello World” without writing a main method. The execution is stopped using “System.exit()” command. So, we prevent “main method not found” error. It's quite a tricky question

提交回复
热议问题