Nandkumar Tekale Nandkumar Tekale - 2 months ago 7
Java Question

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?

Answer
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.)

Comments