Printing message on Console without using main() method

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

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-11-27 03:17

    It was possible till java 6 to use System.out.println(); without main(). From java 7 onwards, it is not possible to do it with static block. It will still ask for main method in main class.

    0 讨论(0)
  • 2020-11-27 03:17

    Actually it doesn't work in the latest update of java 8. You can call it a bug fix according to them, but as far as I believe on my current knowledge this can't be called as a bug fix because it also lead to few conceptual changes too in java programming.

    0 讨论(0)
  • 2020-11-27 03:18

    Yes, you can print a message to console without using main().

    Create a test with JUnit and execute it:

    @Test
    public printTest()   {
       System.out.println("myprint");
    }
    
    0 讨论(0)
  • 2020-11-27 03:19

    If you don't want to use static block too, it can be done following way

    public class NoMain {
    
        private static final int STATUS = getStatus();
    
        private static int getStatus() {
            System.out.println("Hello World!!");
            System.exit(0);
            return 0;
        }
    
    }
    

    However, please note that this is for Java 6 version. Its not working in Java 7 which is said to be supported in Java 8. I tried with JDK 1.8.0_77-b03, which is still not working

    0 讨论(0)
提交回复
热议问题