Printing message on Console without using main() method

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

    Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

    class Withoutmain{  
     static{  
      System.out.println("Message: Your message can be print on console without main() method");  
      System.exit(0);  
     }  
    }  
    

    Output:Message: Your message can be print on console without main() method (if not JDK7)

    Output:Error: Main method not found in class A3, please define the main method as: public static void main(String[] args)

    Reference

提交回复
热议问题