Printing message on Console without using main() method

I was asked this question in an interview.

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


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()

Ideone link

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


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

The static block is first executed as soon as the class is loaded before the main(); method is invoked and therefore before main() is called, System.exit(0) initiates VM shut down.

The System.exit method halts the execution of the current thread and all others dead in their tracks. When System.exit is called, the virtual machine performs two cleanup tasks before shutting down.

First, it executes all shutdown hooks that have been registered with Runtime.addShutdownHook . This is useful to release resources external to the VM. Use shutdown hooks for behavior that must occur before the VM exits.

The second cleanup task performed by the VM when System.exit is called concerns finalizers. If either System.runFinalizersOnExit or its evil twin Runtime.runFinalizersOnExit has been called, the VM runs the finalizers on all objects that have not yet been finalized. These methods were deprecated a long time ago and with good reason. Never call System.runFinalizersOnExit or Runtime.runFinalizersOnExit for any reason: They are among the most dangerous methods in the Java libraries. Calling these methods can result in finalizers being run on live objects while other threads are concurrently manipulating them, resulting in erratic behavior or deadlock.

In summary, System.exit stops all program threads immediately; it does not cause finally blocks to execute, but it does run shutdown hooks before halting the VM. Use shutdown hooks to terminate external resources when the VM shuts down. It is possible to halt the VM without executing shutdown hooks by calling System.halt , but this method is rarely used.


In a file called A.java

class Con {
    String hi = "nnHello Worldnn";
}

You just have to compile the program on Windows. Not run it. :-P

链接地址: http://www.djcxy.com/p/20596.html

上一篇: 将方法名称作为字符串给定时,如何调用Java方法?

下一篇: 在控制台上打印消息而不使用main()方法